import { Component, HostListener, ViewChild, ElementRef } from '@angular/core';
import { IonMenu, IonNav, NavController, Platform } from '@ionic/angular';
import { NzModalModule } from 'ng-zorro-antd/modal';
import { NzDropDownModule } from 'ng-zorro-antd/dropdown';
// import { AuthService } from 'ng-fmode-admin';
// import { FormGroup, FormBuilder, Validators, AbstractControl } from '@angular/forms';
import Parse from "parse";
// import { AccountService } from '../../modules/account/account.service';
import { HttpClient } from '@angular/common/http';
import { NzMessageService } from "ng-zorro-antd/message";
import { Router, RouterModule } from '@angular/router';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { CommonModule } from '@angular/common';
@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss'],
  imports:[
    CommonModule,RouterModule,
    NzButtonModule,NzModalModule,NzDropDownModule,
  ],
  standalone:true,
})
export class HeaderComponent {
  @ViewChild(IonMenu) menu:IonMenu|undefined=undefined
  @ViewChild(IonMenu) userMenu:IonMenu|undefined=undefined
  @ViewChild("canvas") canvas: ElementRef|undefined=undefined; //本地校验码绘画

  //点击登录弹框设置
  isLoginShow = false;

  isVisible:boolean = false //分享弹窗
  imgUrl:string = ""

  openUserMenu(){
    console.log("openUserMenu")
    if(this.navMenuType=="mobile"){
      console.log("mobile");
      this.userMenu?.toggle();
    }
  }
  user:Parse.User|undefined|null
  mobileWidth = 915;
  get leftMenuMode():string{
    let clientWidth = document.body.clientWidth;
    if(clientWidth>=915){
      return "horizontal";
    }else{

      return "inline";
    }
  }
  get navMenuType():string{
    let clientWidth = document.body.clientWidth;
    if(clientWidth>=915){
      return "pc";
    }else{

      return "mobile";
    }
  }
  get clientWidth():number {
    let clientWidth = document.body.clientWidth;
    return clientWidth
  }
  goFeima(){
    window.open("https://www.fmode.cn","_blank")
  }
  isCapacitor:boolean = false
  constructor(
    // public authServ:AuthService,
    // public accServ:AccountService,
    private navCtrl:NavController,
    private platform:Platform,
    private http : HttpClient,
    private message: NzMessageService,
    public router:Router,
    ){
    // this.accServ.getBilling();
    this.isCapacitor = this.platform.is("capacitor")
    this.getCode()
  }
  setRoot(path:string){
    if(this.menu?.close){
      this.menu?.close();
    }
    this.navCtrl.navigateRoot(path);
  }
  async ngOnInit() {
    this.user = await Parse.User.currentAsync()
  }
  logout(){
    // this.authServ.logout(null,"../")
  }

  //海报
  bannerUrl:string = 'https://file-cloud.fmode.cn/UP2cStyjuk/20231113/r1r7em033605088.jpg@3000w_1l_0o_100sh'
  codeUrl:string|undefined = undefined
  async getCode(){
    let uid = (await Parse.User.currentAsync())?.id
    let qrCodeUrl = `https://ai.fmode.cn/?invite=${uid}`;
    let params = {
      qrCode: qrCodeUrl,
      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
    })
  }
  
  onShowModal(){
    this.isVisible = true
    this.drawPoster()
  }
  handleOk(){
    this.onClose()
  }
  onClose(){
    this.isVisible = false
  }
  //绘画海报
  async drawPoster(){
    let canvas:any = document.createElement('canvas')
    canvas.height = '360'
    canvas.width = '200'
    // if(!canvas){
    //   setTimeout(() => {
    //     this.drawPoster()
    //   }, 500);
    //   return
    // }
    let ctx = canvas.getContext('2d');
    //定义图片
    ctx.drawImage(await this.compileImage(this.bannerUrl), 0, 0, 340, 540);
    //绘制二维码
    ctx.drawImage(await this.compileImage(this.codeUrl), 60 ,180, 80, 80);
    let tempSrc = canvas.toDataURL("image/png");
    this.imgUrl = tempSrc;
    document.body.removeChild(canvas);
  }
  compileImage(url?:string): Promise<any>{
    return new Promise((res)=>{
      if(!url) {res(false);return}
      let img = new Image();
      img.src = url;
      img.setAttribute('crossOrigin', 'anonymous');
      img.onload = function() {
        res (img)
      }
    })
  }

  /**
   * 返回当前元素的文本内容
  */
  copyText(){
    let uid = Parse.User.current()?.id
    let text = `https://ai.fmode.cn/?invite=${uid}`;
    let textareaC = document.createElement('textarea');
    textareaC.setAttribute('readonly', 'readonly'); //设置只读属性防止手机上弹出软键盘
    textareaC.value = text;
    // textareaC.style.display = 'none'
    document.body.appendChild(textareaC); //将textarea添加为body子元素
    textareaC.select();
    const res = document.execCommand('copy');
    document.body.removeChild(textareaC);//移除DOM元素
    console.log("复制成功");
    this.message.success("复制成功");
    window.location.href = 'weixin://';
    return res;
  }
  /* 下载海报 */
  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;
    }
  }

  //登录逻辑引用
  /**是否展示登录组件 */
  isLoading:boolean=false

  async goLogin(){
    // let data:any
    if(!Parse.User.current()?.getSessionToken()){
      this.router.navigate(['startup/login'])
      this.isLoading = true
      setTimeout(() => {
        this.goLogin()
      }, 500);
      return
    }
    this.isLoading = false
   
  }

  // createBasicMessage(): void {
  //   this.message.info('请先进行登录');
  // }

  //报名参赛提示框：提示完善个人信息
  // isVisibleSet = false;


  // showModalSet(): void {
  //   this.goLogin();
  //   this.isVisibleSet = true;
  // }

  // handleOkSet(): void {
  //   // console.log('Button ok clicked!');
  //   this.router.navigate(['startup/projectCreate'])
  //   this.isVisibleSet = false;
  // }

  // handleCancelSet(): void {
  //   // console.log('Button cancel clicked!');
  //   this.isVisibleSet = false;
  // }
}
