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

import * as Parse from 'parse';
import { MessageService } from '../../../services/message.service';
import {
  AlertController,
  ionicStandaloneModules,
  LoadingController,
  ScrollDetail,
  ToastController,
} from '../../ionic-standalone.modules';
import { AiChatService } from '../../../services/aichart.service';
import { AccountService } from '../../../services/account.service';
import { DeviceService } from '../../../services/device.service';
import { NavComponent } from '../../../app/components/nav/nav.component';

@Component({
  selector: 'app-online-service',
  templateUrl: './online-service.component.html',
  styleUrls: ['./online-service.component.scss'],
  standalone: true,
  imports: [
    ...ionicStandaloneModules,
    NavComponent,
    FormsModule,
    // DatePipe,
    CommonModule,
    SharedModule,
  ],
})
export class OnlineServiceComponent implements OnInit {

  channel: string = 'admin';
  uid: string = '';
  text: string = '';
  showPreView: boolean = false; //预览图片
  viewImg: string = '';
  height: number = 0;
  showEmoji: boolean = false;
  timer: any;
  currentScroll: number = 0; //滚动条位置
  disabled: boolean = false;

  constructor(
    private router: Router,
    private http: HttpClient,
    // public datePipe: DatePipe,
    private toastController: ToastController,
    private alertController: AlertController,
    private loadingCtrl: LoadingController,
    private activateRoute: ActivatedRoute,
    public msgServe: MessageService,
    public aiServ: AiChatService,
    public accServ: AccountService,
    public deviceSer: DeviceService
  ) {
    msgServe.pageFun = this.updatePage;
    msgServe.pageFun();
  }

  ngOnInit() {
    this.activateRoute.paramMap.subscribe(async (params) => {
      this.channel = this.channel + '-' + Parse.User.current()?.id!;
      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.msgServe.initRTM();
    await this.msgServe.subscribeMessage(
      this.channel,
      {
        message: true,
      }
    ); //订阅消息
    loading.dismiss();
  }


  ngOnDestroy(): void {
    this.msgServe.pageFun = () => {};
    if (!this.uid) {
      this.msgServe.messageMapList[this.channel] = null
      this.msgServe.unsubscribeMessage(this.channel);
    }
  }
  /* 开始滑动 */
  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;
    }
    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.channel);
    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);
  }
}
