import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { AiChatService } from '../../../services/aichart.service';
import { LiveService } from '../../../services/live.service';
import * as Parse from 'parse';
import {
  ionicStandaloneModules,
  AlertController,
  LoadingController,
  ToastController,
} from '../../../modules/ionic-standalone.modules';
import { AccountService } from '../../../services/account.service';
import { MessageService } from '../../../services/message.service';
import { VapInit } from '../../../lib/vap-player/index';
import { RechargeComponent } from '../../../modules/account/recharge/recharge.component';

@Component({
  selector: 'app-gift-modal',
  templateUrl: './gift-modal.component.html',
  styleUrls: ['./gift-modal.component.scss'],
  standalone: true,
  imports: [
    ...ionicStandaloneModules,
    CommonModule,
    FormsModule,
    RechargeComponent,
  ],
})
export class GiftModalComponent implements OnInit {
  @Input('toUid') toUid!: string; // 接收礼物的uid
  @Input('domId') domId: string = 'vap-warp';
  @Input('isRead') isRead: boolean = false
  
  isOpenGift: boolean = false; // 是否显示礼物弹窗
  giftList: Array<any> = [];
  tabs: Array<any> = [
    {
      name: '礼物',
      val: 'all',
    },
    {
      name: '专属礼物',
      val: 'vip',
    },
    {
      name: '守护',
      val: 'guard',
    },
  ];
  activeTab: string = 'all';
  currentGift: any; //当前礼物
  giftCount: number = 1;
  wallet: any = { balance: 0 };
  isShowGiftModal: boolean = false; // 是否显示礼物动效弹窗
  times: any;
  @Output() sendEmit: EventEmitter<any> = new EventEmitter<any>();

  showRechargeModal: boolean = false;
  options: Array<number> = [30, 50, 100, 200, 500, 1000, 2000, 5000];
  company = localStorage.getItem('company');
  account?: Parse.Object;
  loading: any;
  tradeNo: string = ''; //支付单号

  constructor(
    private aiServ: AiChatService,
    private alertController: AlertController,
    public liveService: LiveService,
    private loadingCtrl: LoadingController,
    public accServ: AccountService,
    private toastController: ToastController,
    public msgSerrvice: MessageService
  ) {}
  async ngOnInit() {
    this.giftList = this.msgSerrvice.giftList;
    setTimeout(() => {
      this.selectTab('all',true);
    }, 200);
  }
  async openModal() {
    let uid: any = Parse.User.current()?.id;
    this.wallet = await this.aiServ.getWallet(uid);
    this.isOpenGift = true;
  }
  async selectTab(val: string, force?:boolean) {
    if (this.activeTab === val && !force) return;
    this.giftList = await this.aiServ.getGift(val == 'all' ? '' : val);
    this.activeTab = val;
    this.currentGift = null;
  }
  onChange() {
    this.giftCount = this.giftCount < 1 ? 1 : Math.floor(this.giftCount);
    console.log(this.giftCount);
  }

  async sendGift() {
    let _this = this;
    if (
      !this.wallet?.balance ||
      this.wallet.balance < this.currentGift.price * this.giftCount
    ) {
      const toast = await this.toastController.create({
        message: '余额不足',
        color: 'danger',
        duration: 1000,
      });
      toast.present();
      return;
    }
    if (!this.currentGift?.id || this.giftCount < 1) return;
    const alert = await this.alertController.create({
      cssClass: 'my-custom-class',
      header: '送出礼物',
      message: `确定送出${this.giftCount}件${this.currentGift.name}吗`,
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          cssClass: 'secondary',
          handler: (blah) => {},
        },
        {
          text: '确定',
          handler: async () => {
            const loading = await _this.loadingCtrl.create({
              message: '送出礼物中...',
            });
            loading.present();
            _this.aiServ
              .putGift(_this.toUid, _this.currentGift.id, _this.giftCount)
              .then((data) => {
                console.log(data);
                _this.liveService.get_duration();
                loading.dismiss();
                _this.sendEmit.emit(); //触发父组件的sendEmit事件
                _this.isOpenGift = false;
                // _this.isShowGiftModal = true;
                _this.publishGiftMessage(_this.currentGift.id, _this.giftCount);
                // setTimeout(() => {
                //   _this.isShowGiftModal = false;
                //   console.log(_this.isShowGiftModal);
                //   console.log('5s后关闭');
                // }, 5000);
                setTimeout(() => {
                  this.initPlayer();
                }, 0);
              })
              .catch((err) => {
                _this.isOpenGift = false;
                loading.dismiss();
                console.error(err);
              });
          },
        },
      ],
    });
    await alert.present();
  }

  initPlayer() {
    console.log('送出礼物', this.currentGift);
    let json = this.currentGift.config;
    let dom: any = document.getElementById(this.domId);
    let vapPlayer: any = VapInit({
      container: dom, // 要渲染的载体，dom元素
      src: this.currentGift.video, // vap动画地址
      config: json, // 播放vap动画需要的 json文件。必填
      width: window.innerWidth, // 容器宽度
      height: window.innerHeight, // 容器高度
      fps: json?.info?.fps || 30, // 帧数，json文件中有这个视频的帧数的，可以看一下，
      mute: false, // 静音
      type: 0, // 组件基于type字段做了实例化缓存，不同的VAP实例应该使用不同的type值（如0、1、2等）
      loop: false, // 循环
      precache: true, // 预加载视频，下载完再播。小动画建议边下边播，大动画还是先下后播吧，因为太大了或者网络不好，会一卡一卡的。
      beginPoint: 0, // 起始播放时间点(单位秒),在一些浏览器中可能无效
      accurate: true, // 是否启用精准模式（使用requestVideoFrameCallback提升融合效果，浏览器不兼容时自动降级）
    });
    vapPlayer.play(); // 开始播放
    vapPlayer.on('ended', () => {
      // 监听播放完成的事件
      vapPlayer.destroy();
      vapPlayer = null;
      console.log('play end');
    });
    vapPlayer.on('playering', function () {
      console.log('playering');
    });
  }

  onCloseGiftModal() {
    if (!this.isShowGiftModal) this.isShowGiftModal = false;
  }

  publishGiftMessage(gid: string, count: number) {
    this.msgSerrvice.subscribeMessage(this.toUid, {
      message: true,
      presence: true,
    }); //触发礼物消息
    this.msgSerrvice.publishMessage(
      `ONUSERSENDGIFT_${gid}_${count}`,
      this.toUid
    );
  }

  /* 充值返回结果 */
  async onRecharge(e: any) {
    console.log(e);
    if (e) {
      let uid: any = Parse.User.current()?.id;
      this.wallet = await this.aiServ.getWallet(uid);
      this.liveService.get_duration();
    }
    this.showRechargeModal = false;
  }
}
