import { Component, OnInit } from '@angular/core';
import * as Parse from 'parse';
import { InfiniteScrollCustomEvent } from '@ionic/angular';
import { Router } from '@angular/router';
import { AiChatService } from '../../../services/aichart.service';
import { SharedModule } from '../../shared.module';
import { MessageService } from '../../../services/message.service';
import { ionicStandaloneModules, ToastController } from '../../ionic-standalone.modules';
import { DeviceService } from '../../../services/device.service';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { AccountService } from '../../../services/account.service';
@Component({
  selector: 'app-notice',
  templateUrl: './notice.component.html',
  styleUrls: ['./notice.component.scss'],
  standalone: true,
  imports: [SharedModule, ...ionicStandaloneModules, CommonModule,FormsModule],
})
export class NoticeComponent implements OnInit {
  active: string = 'notice';
  noticeList: Array<any> = [];
  alertButtons = [
    {
      text: '取消',
      role: 'cancel',
      handler: () => {
        console.log('Alert canceled');
      },
    },
    {
      text: '确认',
      role: 'confirm',
      handler: async () => {
        console.log(this.currentFriend);
        let query = new Parse.Query('Friends');
        query.equalTo('channel', this.currentFriend.channel);
        query.equalTo('company', this.msgServe.company);
        query.equalTo('isPass', true);
        query.notEqualTo('isDeleted', true);
        let f = await query.first();
        if (f?.id) {
          let uid = Parse.User.current()?.id!;
          let config = f?.get('config') || {};
          config[uid] = new Date()?.getTime();
          f.set('config', config);
          await f.save();
        }
        this.msgServe.delMsg(this.currentFriend.channel);
      },
    },
  ];
  friends: Array<any> = [];
  times: number = 0;
  timer: any;
  showModal: boolean = false; //是否长按弹窗
  currentObject: any; //当前选择对象
  isOpen: boolean = false;
  codeUrl: string = '';
  notices: Array<any> = [];
  currentFriend: any; //当前选中的好友

  constructor(
    private router: Router,
    private aiSer: AiChatService,
    public accServ: AccountService,
    public msgServe: MessageService,
    private toastController: ToastController,
    public deviceSer: DeviceService
  ) {}

  ngOnInit() {
    this.refresh();
  }
  async refresh() {
    let uid: any = Parse.User.current()?.id;
    let resultFriends = await this.aiSer.getFriends(uid);
    this.friends = resultFriends['data'];
    console.log(this.friends);
    // resChat?.data && this.noticeList.push(...resChat.data);
    this.getSetting();
    // this.getSysNotice()
  }
  async getSetting() {
    let query = new Parse.Query('SiteConfig');
    query.equalTo('company', this.aiSer.company);
    query.notEqualTo('isDeleted', false);
    query.select('wxCode');
    let r = await query.first();
    this.codeUrl = r?.get('wxCode');
  }
  async getSysNotice() {
    let result = await this.aiSer.getSysNotice(Parse.User.current()?.id!);
    this.notices = result.data;
    console.log(this.notices);
  }
  segmentChanged(e: any) {
    let { value } = e.detail;
    this.active = value;
  }
  /* 手指按下 */
  startPress(item: any) {
    this.showModal = false;
    if (this.times >= 500) {
      // console.log(this.times);
      this.times = 0;
      this.currentFriend = item;
      // console.log(this.currentFriend);
      this.showModal = true;
      return;
    }
    this.timer = setTimeout(() => {
      this.times += 500;
      this.startPress(item);
    }, 500);
  }
  /* 触摸屏幕并移动,取消长按事件 */
  onMousemove(e: any) {
    clearTimeout(this.timer);
    // this.showModal = false;
    this.times = 0;
  }
  /* 手指抬起 */
  stopPress() {
    clearTimeout(this.timer);
    this.times = 0;
  }
  onIonInfinite(ev: any) {
    console.log(ev);
    setTimeout(() => {
      (ev as InfiniteScrollCustomEvent).target.complete();
    }, 500);
  }

  toUrl(url: string) {
    if (this.showModal) return;
    this.router.navigate([url]);
  }
  async toUrlService(url: string){
    if (this.showModal) return;
    if(!this.accServ.userVip?.rights?.['vip-service']){
      const toast = await this.toastController.create({
        message: '高级会员专享服务',
        color: 'warning',
        duration: 1500,
      });
      toast.present();
      return
    }
    this.router.navigate([url]);
  }
  async download() {
    let canvas: any = document.createElement('canvas');
    canvas.height = '480';
    canvas.width = '480';
    let ctx = canvas.getContext('2d');
    //绘制二维码
    ctx.drawImage(await this.compileImage(this.codeUrl), 0, 0, 480, 480);
    let tempSrc = canvas.toDataURL('image/png');
    let dlLink: any = document.createElement('a');
    if ('download' in dlLink) {
      dlLink.style.visibility = 'hidden';
      dlLink.href = tempSrc;
      dlLink.download = '分享海报';
      document.body.appendChild(dlLink);
      dlLink.click();
      document.body.removeChild(dlLink);
    } else {
      location.href = tempSrc;
    }
  }

  compileImage(url: string): Promise<any> {
    return new Promise((res) => {
      let img = new Image();
      img.src = url;
      img.setAttribute('crossOrigin', 'anonymous');
      img.onload = function () {
        res(img);
      };
    });
  }

  value: string = '';
  async toSearch() {
    this.friends = []
    let uid: any = Parse.User.current()?.id;
    let resultFriends = await this.aiSer.getFriends(uid,this.value);
    console.log(resultFriends);
    this.friends = resultFriends['data'];
  }
}
