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 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 {
  AlertController,
  ionicStandaloneModules,
  LoadingController,
  ScrollDetail,
  ToastController,
} from '../../ionic-standalone.modules';
import { AiChatService } from '../../../services/aichart.service';
import { AccountService } from '../../../services/account.service';
import { CallModalComponent } from '../../../app/components/call-modal/call-modal.component';
import { AppraiseComponent } from '../../../app/components/appraise/appraise.component';
import { DeviceService } from '../../../services/device.service';

@Component({
  selector: 'app-chat',
  templateUrl: './chat.component.html',
  styleUrls: ['./chat.component.scss'],
  standalone: true,
  imports: [
    ...ionicStandaloneModules,
    FormsModule,
    // DatePipe,
    GiftModalComponent,
    CommonModule,
    SharedModule,
    CallModalComponent,
    AppraiseComponent
  ],
  // providers: [DatePipe],
})
export class ChatComponent implements OnInit {
  @ViewChild('call') call!: CallModalComponent;

  channel: 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;
  friend?: Parse.Object; //好友
  isRet?: Parse.Object; //黑名单

  level: any; //权益
  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) => {
      let id: any = params.get('id');
      this.channel = 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.channel) {
        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.getFriend();
    await this.msgServe.initRTM();
    await this.msgServe.subscribeMessage(
      this.channel,
      {
        message: true,
        // presence: true,
      },
      this.friend?.get('config')?.[Parse.User.current()?.id!]
    ); //订阅消息
    if (this.uid) {
      this.isRet = await this.aiServ.getRetFriends(this.uid);
    }
    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();
    }
  }
  async getFriend() {
    if (!this.uid) return;
    let query = new Parse.Query('Friends');
    query.equalTo('channel', this.channel);
    query.equalTo('company', this.msgServe.company);
    query.equalTo('isPass', true);
    query.notEqualTo('isDeleted', true);
    this.friend = await query.first();
  }
  ngOnDestroy(): void {
    this.msgServe.pageFun = () => {};
    if (!this.uid) {
      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) {
    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.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);
  }

  async deleteChatLog() {
    const alert = await this.alertController.create({
      cssClass: 'my-custom-class',
      header: '',
      message: '你确定删除聊天记录吗？',
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          handler: () => {},
        },
        {
          text: '确定',
          cssClass: 'secondary',
          handler: async (blah) => {
            console.log('Confirm Cancel: blah');
            if (this.uid && this.friend?.id) {
              let uid = Parse.User.current()?.id!;
              let config = this.friend?.get('config') || {};
              config[uid] = new Date()?.getTime();
              this.friend.set('config', config);
              await this.friend.save();
            }
            this.msgServe.delMsg(this.channel);
          },
        },
      ],
    });
    await alert.present();
  }

  async onRjects() {
    const alert = await this.alertController.create({
      cssClass: 'my-custom-class',
      header: '',
      message: `你确定${this.isRet?.get('isAward') ? '移除对方为黑名单列表' : '加入对方为黑名单列表'}吗？`,
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          handler: () => {},
        },
        {
          text: '确定',
          cssClass: 'secondary',
          handler: async (blah) => {
            if (!this.isRet?.id) {
              let obj = Parse.Object.extend('EventLog');
              this.isRet = new obj();
            }
            this.isRet?.set('isAward', !this.isRet?.get('isAward'));
            this.isRet?.set('company', {
              __type: 'Pointer',
              className: 'Company',
              objectId: this.aiServ.company,
            });
            this.isRet?.set('invited', {
              __type: 'Pointer',
              className: '_User',
              objectId: this.uid,
            });
            this.isRet?.set('user', {
              __type: 'Pointer',
              className: '_User',
              objectId: Parse.User.current()?.id!,
            });
            await this.isRet?.save();
            // this.msgServe.delMsg(this.channel);
          },
        },
      ],
    });
    await alert.present();
  }
}
