import { Component, OnInit, ViewChild } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import * as Parse from 'parse';
import { Swiper } from 'swiper';

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';
import {
  ionicStandaloneModules,
  AlertController,
  LoadingController,
  ToastController,
} from '../../ionic-standalone.modules';
import { MessageService } from '../../../services/message.service';
import { FlutterCompComponent } from '../../../app/components/flutter-comp/flutter-comp.component';
import { AvatarComponent } from '../../../app/components/avatar/avatar.component';
import { AccountService } from '../../../services/account.service';
@Component({
  selector: 'app-link-page',
  templateUrl: './link-page.component.html',
  styleUrls: ['./link-page.component.scss'],
  standalone: true,
  imports: [
    ...ionicStandaloneModules,
    FormsModule,
    LiveComponent,
    CommonModule,
    SharedModule,
    GiftModalComponent,
    FlutterCompComponent,
    AvatarComponent,
  ],
})
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;

  text: string = '';
  disabled: boolean = false;
  showEmoji: boolean = false;
  loading: boolean = true;
  userVip: any;
  constructor(
    private toastController: ToastController,
    private loadingCtrl: LoadingController,
    private alertController: AlertController,
    private activateRoute: ActivatedRoute,
    public aiServ: AiChatService,
    private accServ: AccountService,
    public msgServe: MessageService,
    public liveService: LiveService
  ) {
    // msgServe.pageFun = this.updatePage;
    // msgServe.pageFun();
  }

  ngOnInit() {
    this.activateRoute.paramMap.subscribe(async (params) => {
      let rid: any = params.get('rid');
      this.rid = rid;
      if (!this.rid) {
        history.back();
        return;
      }
      this.refresh();
      localStorage.setItem('isLive', 'true');
    });
  }
  updatePage() {
    setTimeout(() => {
      let dom = document.getElementById('liveScrollMsg');
      if (dom) {
        dom.scrollIntoView({
          behavior: 'smooth',
          block: 'end',
          inline: 'nearest',
        });
      }
    }, 500);
  }
  async refresh() {
    const loading = await this.loadingCtrl.create({
      message: '加载中',
    });
    loading.present();
    await this.getRoom();
    this.userVip = await this.accServ.getVip(this.room?.get('user').id);
    this.initSwiperTimeEvent();
    loading.dismiss();
    this.loading = false;
  }
  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);
  }
  initSwiperTimeEvent() {
    // 初始化轮播图
    let swiper = new Swiper('.chartSwiper', {
      loop: false, // 循环模式选项
      observer: false, //修改swiper自己或子元素时，自动初始化swiper
      observeParents: true, //修改swiper的父元素时，自动初始化swiper
    });
    // swiper.on('slideChange', function (event: any) {
    //   // console.log(event);
    // });
  }
  /* 关注状态 */
  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;
    if (this.liveService.connection_state !== 'CONNECTED') {
      this.presentToast('需连接成功后操作');
      return;
    }
    switch (type) {
      case 'audio':
        this.liveService.updatePublishedAudioTrack();
        break;
      case 'camera':
        this.liveService.changeCamera();
        break;
      case 'mute':
        this.liveService.muteAudio();
        break;
      case 'glorify':
        this.liveService.changeBeauty();
        break;
      case 'gift':
        this.gift.openModal();
        break;
      case 'chat':
        break;
    }
  }
  onSendGift() {
    console.log('点击送出礼物');
    this.liveService.get_duration();
  }
  onPage() {
    if (!this.showEmoji) {
      this.showTool = !this.showTool;
    } else {
      this.showEmoji = false;
    }
  }
  /* 结束直播 */
  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();
            if (!this.liveService.isAnchor) {
              this.liveService.isOpenEvaluate = true;
              return;
            }
            // this.onComment();
          },
        },
      ],
    });
    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();
  }
  //添加表情
  emojiChoose(value: any) {
    console.log(value);
    this.text = this.text + value;
  }
  //发送文字
  comfirmText(e?: any) {
    if (e && e.keyCode != 13) {
      return;
    }
    this.disabled = true;
    if (this.text == '' && this.text.trim() == '') {
      this.presentToast('聊天内容不能为空');
      this.disabled = false;
      return;
    }
    this.send({
      msg_type: 'text',
      content: this.text,
    });
  }
  async send(param: { msg_type: string; content: string }) {
    await this.msgServe.publishMessage(
      param.content,
      this.room?.get('user')?.id
    );
    this.text = '';
    this.disabled = false;
  }

  async presentToast(title: string, time?: number, color?: string) {
    const toast = await this.toastController.create({
      message: title,
      duration: time || 1500,
      color: color || 'danger',
    });
    toast.present();
  }
  onExit() {
    this.liveService.client.leave();
    // history.back();
  }

  ngOnDestroy(): void {
    if (this.liveService.isAnchor) {
      this.msgServe.setConnectState(this.currentUser?.id!, 'ONLINE');
    }
    this.msgServe.pageFun = () => {};
  }

  /* 评论 */
  async onComment() {
    const alert = await this.alertController.create({
      cssClass: 'my-custom-class',
      header: '评价',
      message: '对本次直播主播进行评价',
      inputs: [
        {
          name: 'comment',
          placeholder: '评价',
          attributes: {
            maxlength: 20,
          },
        },
        {
          name: 'star',
          type: 'number',
          placeholder: '打分（1-5分）',
          min: 1,
          max: 5,
        },
      ],
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          handler: (data) => {
            this.onExit();
          },
        },
        {
          text: '评价',
          cssClass: 'secondary',
          handler: async (data) => {
            let { comment, star } = data;
            const loading = await this.loadingCtrl.create({
              message: '加载中',
            });
            loading.present();
            star = Math.round(star);
            if (star < 1) star = 1;
            if (star > 5) star = 5;
            console.log(comment, star);
            let obj = Parse.Object.extend('DramaPostLog');
            let postLog = new obj();
            postLog.set('room', {
              __type: 'Pointer',
              className: 'Room',
              objectId: this.room?.id,
            });
            postLog.set('company', {
              __type: 'Pointer',
              className: 'Company',
              objectId: this.accServ?.company,
            });
            postLog.set('user', {
              __type: 'Pointer',
              className: '_User',
              objectId: this.currentUser?.id,
            });
            postLog.set('type', 'comment');
            postLog.set('credit', star);
            postLog.set('comment', comment);
            await postLog.save();
            loading.dismiss();
            this.onExit();
          },
        },
      ],
    });
    await alert.present();
  }
}
