import { DatePipe } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import {
  IonicModule,
  LoadingController,
  ModalController,
  ScrollDetail,
  ToastController,
} from '@ionic/angular';
// import * as JIMServ from '../../services/common/jim';
// var JIM = JIMServ.JIM;
// var Events = JIMServ.Events;
import * as Parse from 'parse';
import { MessageService } from '../../../services/message.service';

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

  ngOnInit() {
    this.activateRoute.paramMap.subscribe(async (params) => {
      let id: any = params.get('id');
      this.uid = id;
      if (!this.uid) {
        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(this.uid)
    await this.msgServe.subscribeMessage(this.uid,{message:true}) //订阅消息
    this.initEmoji();
    loading.dismiss();
  }
  /* 获取用户信息 */
  async getProfile() {
    if (this.uid === 'all') {
      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 = () => {};
    this.msgServe.unsubscribeMessage(this.uid)
  }
  initEmoji() {
    let emojiChar =
      '☺-😋-😌-😍-😏-😜-😝-😞-😔-😪-😁-😂-😃-😅-😆-👿-😒-😓-😔-😏-😖-😘-😚-😒-😡-😢-😣-😤-😢-😨-😳-😵-😷-😸-😻-😼-😽-😾-😿-🙊-🙋-🙏-✈-🚇-🚃-🚌-🍄-🍅-🍆-🍇-🍈-🍉-🍑-🍒-🍓-🐔-🐶-🐷-👦-👧-👱-👩-👰-👨-👲-👳-💃-💄-💅-💆-💇-🌹-💑-💓-💘-🚲';

    let emojiKey = [
      '60a',
      '60b',
      '60c',
      '60d',
      '60f',
      '61b',
      '61d',
      '61e',
      '61f',
      '62a',
      '62c',
      '602',
      '603',
      '605',
      '606',
      '608',
      '612',
      '613',
      '614',
      '615',
      '616',
      '618',
      '619',
      '620',
      '621',
      '623',
      '624',
      '625',
      '627',
      '629',
      '633',
      '635',
      '637',
      '63a',
      '63b',
      '63c',
      '63d',
      '63e',
      '63f',
      '64a',
      '64b',
      '64f',
      '681',
      '68a',
      '68b',
      '68c',
      '344',
      '345',
      '346',
      '347',
      '348',
      '349',
      '351',
      '352',
      '353',
      '414',
      '415',
      '416',
      '466',
      '467',
      '468',
      '469',
      '470',
      '471',
      '472',
      '473',
      '483',
      '484',
      '485',
      '486',
      '487',
      '490',
      '491',
      '493',
      '498',
      '6b4',
    ];
    let emojis = [];
    let emojiCharArr = emojiChar.split('-');
    for (let i in emojiKey) {
      let em = {
        char: emojiCharArr[i],
        emoji: '0x1f' + emojiKey[i],
      };
      emojis.push(em);
    }
    this.emojis = emojis;
  }
  /* 开始滑动 */
  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) {
    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;
    }
    if (this.text == '' && this.text.trim() == '') {
      this.presentToast('聊天内容不能为空');
      return;
    }
    this.send({
      msg_type: 'text',
      content: this.text,
    });
    this.text = '';
  }
  async send(param: { msg_type: string; content: string }) {
    this.msgServe.publishMessage(param.content, this.uid);
  }
  dismiss(evt: any) {
    this.isOpen = false;
  }
  predivimg<T>(value: string) {
    this.showPreView = true;
    this.viewImg = value;
  }
  onBack() {
    history.back();
  }
  async presentToast(title: string, time?: number, color?: string) {
    const toast = await this.toastController.create({
      message: title,
      duration: time || 1500,
      color: color || 'danger',
    });
    toast.present();
  }
}
