import { Component, OnInit, ViewChild } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import * as Parse from 'parse';
import {
  AlertController,
  IonicModule,
  LoadingController,
  ToastController,
} from '@ionic/angular';
import { ActivatedRoute } from '@angular/router';
import { LiveComponent } from '../../../app/components/live/live.component';
import { LiveService } from '../../../services/live.service';
import { SharedModule } from '../../shared.module';
import { AiChatService } from '../../../services/aichart.service';
import { GiftModalComponent } from '../../../app/components/gift-modal/gift-modal.component';
@Component({
  selector: 'app-link-page',
  templateUrl: './link-page.component.html',
  styleUrls: ['./link-page.component.scss'],
  standalone: true,
  imports: [
    IonicModule,
    FormsModule,
    LiveComponent,
    CommonModule,
    SharedModule,
    GiftModalComponent,
  ],
})
export class LinkPageComponent implements OnInit {
  @ViewChild('live') live!: LiveComponent;
  currentUser?: Parse.Object = Parse.User.current(); //当前登录用户
  rid?: string;
  room?: Parse.Object;
  isFollow: boolean = false;
  showTool: boolean = true; // 是否显示工具栏
  @ViewChild('gift') gift!: GiftModalComponent;

  constructor(
    public toastController: ToastController,
    private loadingCtrl: LoadingController,
    private alertController: AlertController,
    private activateRoute: ActivatedRoute,
    private aiServ: AiChatService,
    public liveService: LiveService
  ) {}

  ngOnInit() {
    this.activateRoute.paramMap.subscribe(async (params) => {
      let rid: any = params.get('rid');
      this.rid = rid;
      if (!this.rid) {
        history.back();
        return;
      }
      this.refresh();
    });
  }
  async refresh() {
    const loading = await this.loadingCtrl.create({
      message: '加载中',
    });
    loading.present();
    await this.getRoom();
    loading.dismiss();
  }
  async getRoom() {
    let query = new Parse.Query('Room');
    query.equalTo('objectId', this.rid);
    query.notEqualTo('isDeleted', true);
    query.include('user');
    query.select('user');
    this.room = await query.first();
    this.getFollwState(this.room?.get('user').id);
  }
  /* 关注状态 */
  async getFollwState(uid: string) {
    let query = new Parse.Query('ProfileRadar');
    query.equalTo('toUser', uid);
    query.equalTo('fromUser', this.currentUser?.id);
    query.notEqualTo('isDeleted', true);
    query.equalTo('name', '关注');
    let r = await query.first();
    this.isFollow = r?.id ? true : false;
  }
  /* 关注 */
  async onCollection() {
    let query = new Parse.Query('ProfileRadar');
    query.equalTo('toUser', this.room?.get('user').id);
    query.equalTo('fromUser', this.currentUser?.id);
    // query.notEqualTo('isDeleted', true);
    query.equalTo('name', '关注');
    let profileRadar = await query.first();
    if (!profileRadar?.id) {
      let radar = Parse.Object.extend('ProfileRadar');
      profileRadar = new radar();
      profileRadar?.set('toUser', {
        __type: 'Pointer',
        className: '_User',
        objectId: this.room?.get('user').id,
      });
      profileRadar?.set('company', {
        __type: 'Pointer',
        className: 'Company',
        objectId: this.currentUser?.get('company')?.id,
      });
      profileRadar?.set('fromUser', this.currentUser?.toPointer());
      profileRadar?.set('name', '关注');
    }
    profileRadar?.set('isDeleted', this.isFollow);
    await profileRadar?.save();
    this.isFollow = !this.isFollow;
  }
  /* 直播状态 */
  async onChangeLiveStatus(e: any, type: string) {
    e.cancelBubble = true;
    switch (type) {
      case 'audio':
        this.liveService.updatePublishedAudioTrack();
        break;
      case 'camera':
        this.liveService.changeCamera();
        break;
      case 'mute':
        this.liveService.muteAudio();
        break;
      case 'gift':
        this.gift.openModal();
        break;
    }
  }
  onSendGift() {
    console.log('点击送出礼物');
    this.liveService.get_duration()
  }
  /* 结束直播 */
  async endCall(e: any) {
    e.cancelBubble = true;
    const alert = await this.alertController.create({
      cssClass: 'my-custom-class',
      header: '退出提示',
      message: '你确定退出登录吗？',
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          handler: (blah) => {},
        },
        {
          text: '确定',
          cssClass: 'secondary',
          handler: () => {
            console.log('Confirm Cancel: blah');
            this.onExit();
          },
        },
      ],
    });
    await alert.present();
  }
  async onReport(e: any) {
    e.cancelBubble = true;
    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: (data) => {
            let report = data.report;
            console.log(report);
          },
        },
      ],
    });
    await alert.present();
  }
  onExit() {
    this.liveService.client.leave();
    history.back();
  }
}
