import {ApplicationRef, Component, ElementRef, EventEmitter, Input, OnChanges, OnDestroy, Output, ViewChild} from '@angular/core';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
import { NzMessageService, UploadXHRArgs, UploadFile } from 'ng-zorro-antd';


@Component({
  selector: 'app-sub-template',
  templateUrl: './sub-template.component.html',
  styleUrls: ['./sub-template.component.scss']
})
export class SubTemplateComponent implements OnDestroy, OnChanges {
  uploading = false;
  progress = 0;
 
  
  @Output()
  save = new EventEmitter();

  @Output()
  deleteFunc = new EventEmitter();

  @Output()
  refreshEmitter = new EventEmitter();

  @Input()
  set item(v) {

    console.log('set item: ', v);

    if (this.uploadUrl) {
      this._item = v;
      console.log(' __  refreshSafeUrl 3')
      this.refreshSafeUrl();
    }
    this._data = v;
  }

  get item() {
    return this._data;
  }

  _item;
  _data;



  @Input()
  key = '';

  uploadUrl;
  uploadData;

  @ViewChild('iframe', {static: true }) iframe: ElementRef;
  isShowTemplate = false;

  constructor(private el:ElementRef, private appRef: ApplicationRef, private nzMessageService: NzMessageService, private sanitizer: DomSanitizer) {


    console.log(' in constructor 1111:', window['air']);

    
    this.uploadUrl = (<any> window).courseware.uploadUrl();
    this.uploadData = (<any> window).courseware.uploadData();

    window['air'].getUploadCallback = (url, data) => {

      this.uploadUrl = url;
      this.uploadData = data;
    };

    this.setUploadUrl();
  }


  setUploadUrl() {

    if (!this.uploadUrl) {

      setTimeout(() => {
        this.setUploadUrl();
      }, 500);
    } else {

      if (this._data) {

        this._item = this._data;
        this.refreshSafeUrl()
      }

    }
  }

  safeUrl;
  refreshSafeUrl(formUrl=null) {
    if (!formUrl) {
      formUrl = this._item.formUrl || '';
    }

    this.safeUrl = this.sanitizer.bypassSecurityTrustResourceUrl(formUrl); 

  }

  
  ngOnChanges() {
 
  }

  isInit = false;
  ngOnInit(): void {



    console.log(' in ngOnInit ')
    if (!this._item) {
      this._item = {};
    }

    
    this.initListener();

  }

  

  templateArr = [];
  async selectSubTemplate() {

    if (this.templateArr.length == 0) {
      await this.getAllTemplateData().then((data : []) => {
        this.templateArr = data;
      });
    }

    this.isShowTemplate = true;
  }

  deleteSubTemplate() {
    
    console.log('in deleteFunc');
    this.refreshSafeUrl('');
    this.deleteFunc.emit({});
  }


  templateClick(template) {
    console.log("template: ", template);

    this._item = {};

    const {name, last_version, form_url} = template;
    const formUrl = `http://staging-teach.cdn.ireadabc.com/h5template/${name}/v${last_version}/${form_url}&key=${this.key}`

    this._item.formUrl = formUrl;
    this._item.template = template;

    console.log('formUrl: ', formUrl)
    
    this.refreshSafeUrl();
    this.closePanel();
    this.sendData();

    console.log('this.safeUrl 2 : ', this.safeUrl)

    // const key = this.getQueryVariable(formUrl, 'key');
    // console.log("key: ", key);
    // console.log("url: ",  this._item['safeUrl']);
  }

  sendData() {
    this.save.emit(this._item)
  }

  getQueryVariable(url, variable) {
    var query = url.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
      var pair = vars[i].split("=");
      if(pair[0] == variable){return pair[1];}
    }
    return(false);
  }

  saveSubTemplate() {

  }

  initListener() {

  
    const msgFunc = (e) => {


      if (!this.iframe || !this.iframe.nativeElement || !this.iframe.nativeElement.contentWindow) {
        console.log('this.iframe not exist'); 
        window.removeEventListener('message', msgFunc);
        return;
      }

      let msgData = e.data;
  
      if (msgData.action === "getData") {

        console.log("getData e: ", e);

        if (this.iframe) {
          console.log('ifram exist: ', this.iframe);
        }
  

        if (!msgData.urlParams) {
          console.log(' !msgData.urlParams: ' , msgData)
          return;
        }
  
        const key = this.getQueryVariable(msgData.urlParams, 'key');
        if (key != this.key) {
          console.log(' key != this.key ')
          return;
        }


         const data = { msg: 'success', data:  JSON.stringify(this._item.data)};
        //  iframeContent.postMessage( { action: 'getData', data: JSON.stringify(data) }, '*');
        this.iframe.nativeElement.contentWindow.postMessage( { action: 'getData', data: JSON.stringify(data) }, '*');

      }
  

      if (msgData.action === "setData") {

        if (!msgData.urlParams) {
          console.log(' !msgData.urlParams: ' , msgData)
          return;
        }
  
        const key = this.getQueryVariable(msgData.urlParams, 'key');
        if (key != this.key) {
          console.log(' key != this.key ')
          return;
        }

        console.log("setData e: ", e);


        
        if (typeof(msgData.data)  === "string") {
          console.log('msgData is string');
          msgData.data = JSON.parse(msgData.data);
          console.log('msgData.data: ', msgData.data);
        }
        this._item.data = msgData.data;
        this.sendData();
      }
     

      if (msgData.action === "getUpload") {

        console.log( ' in getUpload')



        // const iframeContent = this.el.nativeElement.querySelector('#iframe').contentWindow;
   
        
        this.iframe.nativeElement.contentWindow.postMessage({
          action: 'getUpload',
          uploadUrl: this.uploadUrl,
          uploadData: this.uploadData
        }, '*');
      }
    }


    if (this.iframe?.nativeElement?.contentWindow) {
      console.log(' init Listener !');
      window.addEventListener('message', msgFunc);

    }
    
  }

  async getAllTemplateData() {

    return new Promise((resolve, reject) => {

      const c = window['courseware']

      try {
        if (c && c.getTemplates) {
          c.getTemplates((data) => {


            // data =
            // [
            //   {"id": 26, "uuid":"c94fb1b0-3395-42ca-9ae3-03ca7c242d3f", "name": "hw_001", "description": "音频课件", "cover": "http://iplayabc-teach-yun.oss-cn-beijing.aliyuncs.com/3feddb01-4350-42ad-909f-236ad052fbb2.jpg", "type": 1, "t_type": 2, "form_url": "index.html?type=form", "play_url": "index.html", "last_version": 16},
            //   {"id": 27, "uuid":"b8bedc68-9ef6-42a6-ba99-513daa244a6d", "name": "hw_002", "description": "视频课件", "cover": "http://iplayabc-teach-yun.oss-cn-beijing.aliyuncs.com/1b11d370-9d8b-4358-98d3-4757f825d2a4.jpg", "type": 1, "t_type": 2, "form_url": "index.html?type=form", "play_url": "index.html", "last_version": 16},
            //   {"id": 28, "uuid":"068fcffb-4e99-4148-bc8e-2a89ee9bfe7c", "name": "hw_003", "description": "转盘课件", "cover": "http://iplayabc-teach-yun.oss-cn-beijing.aliyuncs.com/de3d8498-7523-4601-934e-932ac219a408.jpg", "type": 1, "t_type": 2, "form_url": "index.html?type=form", "play_url": "index.html", "last_version": 17},
            //   {"id": 29, "uuid":"b2bfd8df-e0e4-41c9-b65f-12160628e1a3", "name": "hw_004", "description": "连线课件", "cover": "http://iplayabc-teach-yun.oss-cn-beijing.aliyuncs.com/824989ac-78fb-4db7-848a-790cba00effe.jpg", "type": 1, "t_type": 2, "form_url": "index.html?type=form", "play_url": "index.html", "last_version": 9 },
            //   {"id": 30, "uuid":"d7be3c21-fc25-482d-a4a6-1a371970457a", "name": "hw_005", "description": "分类课件", "cover": "http://iplayabc-teach-yun.oss-cn-beijing.aliyuncs.com/aa69d85a-3430-48b2-91bf-a804dee1826d.jpg", "type": 1, "t_type": 2, "form_url": "index.html?type=form", "play_url": "index.html", "last_version": 19},
            //   {"id": 31, "uuid":"34e98c65-f3f0-46e4-a7b8-5caf72954847", "name": "hw_006", "description": "翻卡游戏", "cover": "http://iplayabc-teach-yun.oss-cn-beijing.aliyuncs.com/fe54031b-7879-4c65-8de7-102fa5e5e9f5.png", "type": 1, "t_type": 2, "form_url": "index.html?type=form", "play_url": "index.html", "last_version": 5 }
            // ]
            // resolve(data);
            // return
            if (data) {
              console.log('data~~~:', data);
              resolve(JSON.parse(data));
            } else {
              console.log('data none');
              resolve([]);
            }
          })
        }
        
      } catch (error) {
        reject(error);
      }
    })
    // const data =
    // [
    //   {"id": 26, "uuid":"c94fb1b0-3395-42ca-9ae3-03ca7c242d3f", "name": "hw_001", "description": "音频课件", "cover": "http://iplayabc-teach-yun.oss-cn-beijing.aliyuncs.com/3feddb01-4350-42ad-909f-236ad052fbb2.jpg", "type": 1, "t_type": 2, "form_url": "index.html?type=form", "play_url": "index.html", "last_version": 16},
    //   {"id": 27, "uuid":"b8bedc68-9ef6-42a6-ba99-513daa244a6d", "name": "hw_002", "description": "视频课件", "cover": "http://iplayabc-teach-yun.oss-cn-beijing.aliyuncs.com/1b11d370-9d8b-4358-98d3-4757f825d2a4.jpg", "type": 1, "t_type": 2, "form_url": "index.html?type=form", "play_url": "index.html", "last_version": 16},
    //   {"id": 28, "uuid":"068fcffb-4e99-4148-bc8e-2a89ee9bfe7c", "name": "hw_003", "description": "转盘课件", "cover": "http://iplayabc-teach-yun.oss-cn-beijing.aliyuncs.com/de3d8498-7523-4601-934e-932ac219a408.jpg", "type": 1, "t_type": 2, "form_url": "index.html?type=form", "play_url": "index.html", "last_version": 17},
    //   {"id": 29, "uuid":"b2bfd8df-e0e4-41c9-b65f-12160628e1a3", "name": "hw_004", "description": "连线课件", "cover": "http://iplayabc-teach-yun.oss-cn-beijing.aliyuncs.com/824989ac-78fb-4db7-848a-790cba00effe.jpg", "type": 1, "t_type": 2, "form_url": "index.html?type=form", "play_url": "index.html", "last_version": 9 },
    //   {"id": 30, "uuid":"d7be3c21-fc25-482d-a4a6-1a371970457a", "name": "hw_005", "description": "分类课件", "cover": "http://iplayabc-teach-yun.oss-cn-beijing.aliyuncs.com/aa69d85a-3430-48b2-91bf-a804dee1826d.jpg", "type": 1, "t_type": 2, "form_url": "index.html?type=form", "play_url": "index.html", "last_version": 19},
    //   {"id": 31, "uuid":"34e98c65-f3f0-46e4-a7b8-5caf72954847", "name": "hw_006", "description": "翻卡游戏", "cover": "http://iplayabc-teach-yun.oss-cn-beijing.aliyuncs.com/fe54031b-7879-4c65-8de7-102fa5e5e9f5.png", "type": 1, "t_type": 2, "form_url": "index.html?type=form", "play_url": "index.html", "last_version": 5 }
    // ]

    // return data;
  }






  /**
   * 刷新 渲染页面
   */
  refresh() {

    // this.refreshEmitter.emit();
    setTimeout(() => {
      this.appRef.tick();
    }, 1);
  }


  closePanel() {
    console.log(' in closePanel ');
    // this.refresh();
    this.isShowTemplate = false;
  }

  panelCancelClicked() {
    this.isShowTemplate = false;

  }

  panelOkClicked() {
    this.isShowTemplate = false;

  }

  ngOnDestroy() {

  }

}
