import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import * as Parse from 'parse';
import {
  IonicModule,
  LoadingController,
  ModalController,
  ToastController,
} from '@ionic/angular';
import { ActivatedRoute } from '@angular/router';
import { LiveComponent } from '../../../app/components/live/live.component';
@Component({
  selector: 'app-link-page',
  templateUrl: './link-page.component.html',
  styleUrls: ['./link-page.component.scss'],
  standalone: true,
  imports: [IonicModule, FormsModule,LiveComponent],
})
export class LinkPageComponent implements OnInit {
  currentUser?: Parse.Object = Parse.User.current(); //当前登录用户
  rid?: string;
  room?: Parse.Object;
  isFollow: boolean = false;

  constructor(
    public toastController: ToastController,
    private loadingCtrl: LoadingController,
    private activateRoute: ActivatedRoute
  ) {}

  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: '加载中',
    });
    this.getRoom();
    loading.present();
    loading.dismiss();
  }
  async getRoom() {
    let query = new Parse.Query('Room');
    query.equalTo('objectId', this.rid);
    query.notEqualTo('isDeleted', true);
    query.include('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', this.currentUser?.id);
    query.equalTo('fromUser', uid);
    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;
  }
  onExit(){
    history.back()
  }
}
