import { HttpClient } from '@angular/common/http';
import { Component, Input, OnInit } from '@angular/core';
import { ToastController } from '@ionic/angular';
import { NavComponent } from '../../../app/components/nav/nav.component';
import * as Parse from 'parse';
import { ionicStandaloneModules } from '../../ionic-standalone.modules';
import { Router } from '@angular/router';
import { CommonModule, DatePipe } from '@angular/common';
import { AiChatService } from '../../../services/aichart.service';

@Component({
  selector: 'app-share',
  templateUrl: './share.component.html',
  styleUrls: ['./share.component.scss'],
  standalone: true,
  imports: [...ionicStandaloneModules, NavComponent,CommonModule],
  providers: [DatePipe],
})
export class ShareComponent implements OnInit {
  @Input() path: string = '/chat/home';

  imgUrl: string = '';
  //海报
  bannerUrl: string =
    'https://file-cloud.fmode.cn/Qje9D4bqol/20241220/qvj1bm054428527.png';
  codeUrl: string = '';
  list:Array<Parse.Object> = []
  url:string = 'https://chat.gdchat.cn' //分享链接
  constructor(
    private toastController: ToastController,
    private aiServ: AiChatService,
    private router: Router,
    private http: HttpClient
  ) {}

  async ngOnInit() {
    await this.getBanner()
    this.getCode()
    this.getInvite()
  }
  async getInvite(){
    let uid = Parse.User.current()?.id;
    let query = new Parse.Query('User')
    query.equalTo('invite',uid)
    query.skip(this.list.length)
    query.limit(20)
    let res = await query.find()
    this.list.push(...res)
  }
  ngOnChanges() {
    this.getCode();
  }
  async getBanner() {
    let type = 'user'
    if(Parse.User.current().get('agentLevel')){
      type = 'union'
    }else if(this.aiServ.identity){
      type = 'uanchor'
    }
    let query = new Parse.Query('Banner');
    query.equalTo('company', this.aiServ.company);
    query.descending('index');
    query.equalTo('isEnabled', true);
    query.equalTo('type', type);
    query.notEqualTo('isDeleted', true);
    let res = await query.first();
    if(res?.id){
      this.bannerUrl = res?.get('image');
      this.url = res?.get('url');
    }
  }
  getCode() {
    console.log('getcode');
    let uid = Parse.User.current()?.id;
    let params = {
      qrCode: this.url + `?invite=${uid}`,
      darkColor: '#ffffff',
      lightColor: '#000000',
    };
    this.http
      .get('https://server.fmode.cn/api/common/qrcode', { params })
      .subscribe((res: any) => {
        // console.log(res);
        this.codeUrl = res.data;
        this.drawPoster();
      });
  }

  //绘画海报
  async drawPoster() {
    let canvas: any = document.createElement('canvas');
    canvas.height = '480';
    canvas.width = '300';
    let ctx = canvas.getContext('2d');
    //定义图片
    ctx.drawImage(await this.compileImage(this.bannerUrl), 0, 0, 340, 540);
    //绘制二维码
    ctx.drawImage(await this.compileImage(this.codeUrl), 80, 150, 148, 148);
    let tempSrc = canvas.toDataURL('image/png');
    this.imgUrl = tempSrc;
    document.body.removeChild(canvas);
  }
  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);
      };
    });
  }

  /**
   * 返回当前元素的文本内容
   */
  async copyText() {
    let uid = Parse.User.current()?.id;
    let text = this.url + `?invite=${uid}`;
    // let oInput = document.createElement("input");
    // oInput.value = text;
    // document.body.appendChild(oInput);
    // oInput.select(); // 选择对象
    // oInput.setAttribute("readonly", "readonly"); //设置只读属性防止手机上弹出软键盘
    // document.execCommand("Copy"); // 执行浏览器复制命令
    // oInput.style.display = "none";
    // document.body.removeChild(oInput); //移除DOM元素

    navigator.clipboard.writeText(text);
    console.log(text);
    console.log('复制成功');
    const toast = await this.toastController.create({
      message: '复制成功',
      color: 'success',
      duration: 1000,
    });
    toast.present();
    window.location.href = 'weixin://';
  }
  /* 下载海报 */
  downImg() {
    let dlLink: any = document.createElement('a');
    if ('download' in dlLink) {
      dlLink.style.visibility = 'hidden';
      dlLink.href = this.imgUrl;
      dlLink.download = '分享海报';
      document.body.appendChild(dlLink);
      dlLink.click();
      document.body.removeChild(dlLink);
    } else {
      location.href = this.imgUrl;
    }
  }
  toUrl(id: string) {
    this.router.navigate(['/user/profile/' + id]);
  }
}
