import { DatePipe, CommonModule } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { SharedModule } from '../../shared.module';

// import * as JIMServ from '../../services/common/jim';
// var JIM = JIMServ.JIM;
// var Events = JIMServ.Events;
import * as Parse from 'parse';
import { GiftModalComponent } from '../../../app/components/gift-modal/gift-modal.component';
import { MessageService } from '../../../services/message.service';
import {
  ionicStandaloneModules,
  LoadingController,
  ScrollDetail,
  ToastController,
} from '../../ionic-standalone.modules';
import { AiChatService } from '../../../services/aichart.service';
import { AccountService } from '../../../services/account.service';

@Component({
  selector: 'app-chat',
  templateUrl: './chat.component.html',
  styleUrls: ['./chat.component.scss'],
  standalone: true,
  imports: [
    ...ionicStandaloneModules,
    FormsModule,
    // DatePipe,
    GiftModalComponent,
    CommonModule,
    SharedModule,
  ],
  // providers: [DatePipe],
})
export class ChatComponent implements OnInit {
  channle: string = '';
  uid: string = '';
  profile?: Parse.Object; // 对方身份
  targetUser?: Parse.Object; // 对方用户
  text: string = '';
  showPreView: boolean = false; //预览图片
  viewImg: string = '';
  height: number = 0;
  showEmoji: boolean = false;
  timer: any;
  currentScroll: number = 0; //滚动条位置
  disabled: boolean = false;
  level:any //权益
  constructor(
    private router: Router,
    private http: HttpClient,
    // public datePipe: DatePipe,
    public toastController: ToastController,
    private loadingCtrl: LoadingController,
    private activateRoute: ActivatedRoute,
    public msgServe: MessageService,
    public aiServ: AiChatService,
    public accServ: AccountService
    ) {
    msgServe.pageFun = this.updatePage;
    msgServe.pageFun();
  }

  ngOnInit() {
    this.activateRoute.paramMap.subscribe(async (params) => {
      let id: any = params.get('id');
      this.channle = id;
      if (id !== 'global_room') {
        const us = id.split('-');
        const current = Parse.User.current()?.id!;
        this.uid = us.find((item: string) => item !== current);
      }
      if (!this.channle) {
        history.back();
        return;
      }
      this.refresh();
    });
  }
  updatePage() {
    setTimeout(() => {
      let dom = document.getElementById('scrollMsg');
      if (dom) {
        dom.scrollIntoView({
          behavior: 'smooth',
          block: 'end',
          inline: 'nearest',
        });
      }
    }, 500);
  }
  async refresh() {
    const loading = await this.loadingCtrl.create({
      message: '加载中',
    });
    loading.present();
    await this.getProfile();
    await this.msgServe.initRTM();
    await this.msgServe.subscribeMessage(this.channle, {
      message: true,
      // presence: true,
    }); //订阅消息
    loading.dismiss();
  }
  /* 获取用户信息 */
  async getProfile() {
    if (!this.uid) {
      return;
    }
    let queryProfile = new Parse.Query('Profile');
    queryProfile.equalTo('user', this.uid);
    queryProfile.notEqualTo('isDeleted', true);
    queryProfile.include('user');
    let p = await queryProfile.first();
    this.profile = p;
    if (this.profile?.id) {
      this.targetUser = this.profile?.get('user');
    } else {
      let queryUser = new Parse.Query('_User');
      queryUser.equalTo('objectId', this.uid);
      this.targetUser = await queryUser.first();
    }
  }
  ngOnDestroy(): void {
    this.msgServe.pageFun = () => {};
    if (!this.uid) {
      this.msgServe.unsubscribeMessage(this.channle);
    }
  }
  /* 开始滑动 */
  handleScrollStart() {
    // console.log('scroll start');
  }
  /* 滑动中 */
  handleScroll(ev: CustomEvent<ScrollDetail>) {
    let srcollop = ev.detail.scrollTop;
    this.currentScroll = srcollop;
  }
  /* 结束滚动 */
  async handleScrollEnd() {
    console.log(this.currentScroll);
    if (this.currentScroll === 0) {
      this.timer && clearTimeout(this.timer);
      const loading = await this.loadingCtrl.create({
        message: '消息加载中',
        duration: 1500,
      });
      loading.present();
      this.timer = setTimeout(() => {}, 500);
    }
  }
  //调起表情
  changeShowEmoji(isClose?: boolean) {
    if(!this.uid && !this.accServ.userVip?.rights?.['all-chat']) return
    this.showEmoji = isClose ? false : !this.showEmoji;
    this.height = 0;
  }
  //添加表情
  emojiChoose(value: any) {
    console.log(value);
    this.text = this.text + value;
  }
  //删除表情
  delEmoji() {
    this.text = this.text.substring(0, this.text.length - 2);
  }
  //发送文字
  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.channle);
    this.text = '';
    this.disabled = false;
  }
  predivimg<T>(value: string) {
    this.showPreView = true;
    this.viewImg = value;
  }
  onBack() {
    history.back();
  }
  onSendGift() {
    console.log('点击送出礼物');
    // this.liveService.get_duration()
  }
  async presentToast(title: string, time?: number, color?: string) {
    const toast = await this.toastController.create({
      message: title,
      duration: time || 1500,
      color: color || 'danger',
    });
    toast.present();
  }
  toUrl(url: string) {
    this.router.navigateByUrl(url);
  }
}
