require('./index.less');
import { goApp } from './tpl/components/util';
import track from '@apis/track';
import { getUrlParameter } from '@js/utils';

export default class GameReflux {
  constructor(opts) {
    this.opts = opts;
    this.tpl = '';
    this.parentNode = $('body');
    this.wrapper = document.createElement('div');
    this.opts.content = this.content = document.createElement('div');
    this.mask = document.createElement('div');
    this.opts.__track = event => {
      if (event == 'download_show') {
        track(900, {
          share_source: getUrlParameter('share_source')
        });
      } else {
        window.MtaH5 && window.MtaH5.clickStat('common_' + event);
        console.log('MTA====>', 'common_' + event);
      }
    };
    this.init();
  }
  init() {
    if (!this.opts || !this.opts.type) {
      throw new Error('GameReflux:输入正确的初始化参数');
    }

    // render
    this.tpl = require(`./tpl/type${this.opts.type}/index.html`);
    $(this.wrapper).addClass(`game-reflux-mask-wrapper`);
    $(this.mask).addClass(`game-reflux-mask`);
    $(this.content)
      .addClass(`game-reflux-content game-reflux-type${this.opts.type}`)
      .data('type', this.opts.type)
      .html(this.tpl);
    this.wrapper.appendChild(this.content);
    this.wrapper.appendChild(this.mask);
    this.parentNode.append(this.wrapper);

    require(`./tpl/type${this.opts.type}/index.js`)(this.opts);

    this.bindEvent();
  }
  bindEvent() {
    var self = this;
    $('.game-reflux-download').on('click', function() {
      $('body').trigger($(this).data('eventname'), {
        type: self.opts.type
      });
      goApp(self.opts.appLink);
    });
    $('.game-reflux-close').on('click', function() {
      $(self.wrapper).remove();
      $('body').trigger('pop-close', {
        type: self.opts.type
      });
    });
  }
  destroy() {
    this.wrapper.remove();
  }
}
