/**
 *@author liuhaixiao
 *@createTime 2018-11-28 15:57
 *@description 水波纹
 pixi的步骤如下：
 1、创建一个舞台 (stage)
 2、创建一个画布 (render)
 3、把画布插入DOM中
 4、创建一个精灵 (sprite)
 5、把精灵加入画布
 6、把画布加入舞台
 7、刷新舞台
 */
var PIXI = require('../pixi.min');

export default class WaterRipple {
  constructor(select) {
    this.oC = select;
    this.widthCanvas = this.oC.width;
    this.heightCanvas = this.oC.height;
    this.oGc = this.oC.getContext('webgl');
  }

  init(backgroundImage) {
    this.autoPlaySpeed       = [10, 3];
    //创建一个画布
    this.renderer = new PIXI.WebGLRenderer(this.widthCanvas, this.heightCanvas, {antialias: false,canvas:this.oC, context: this.oGc, preserveDrawingBuffer: true});
    //创建一个舞台
    this.stage = new PIXI.Container();
    //创建一个舞台
    this.slidesContainer = new PIXI.Container();
    //使用图片方式创建背景精灵
    this.backgroundImageSprite = new PIXI.Sprite.fromImage('https://dm.static.elab-plus.com/static/img/waterclouds.jpg');
    this.displacementFilter = new PIXI.filters.DisplacementFilter(this.backgroundImageSprite);
    this.initPixi();
    this.loadPixiSprites(backgroundImage);
  }

  initPixi() {
    /*var bgLayers = document.querySelectorAll( '.bg-layer');
    if (null != bgLayers && bgLayers.length>0) {
      this.bgLayer = bgLayers[1];
    }*/
    //把子容器装进舞台中
    this.stage.addChild(this.slidesContainer);
    this.stage.interactive = true;
    this.backgroundImageSprite.texture.baseTexture.wrapMode = PIXI.WRAP_MODES.REPEAT;
    this.stage.filters = [this.displacementFilter];
    this.backgroundImageSprite.scale.x = 2;
    this.backgroundImageSprite.scale.y = 2;
    this.displacementFilter.autoFit = false;
    this.stage.addChild(this.backgroundImageSprite);
  }

  loadPixiSprites(backgroundImage) {
    //初始化时，加载背景图片，使之动效在背景图上进行展示，如果没有背景图，则显示不出
    /*var bgImage;
    if (null != this.bgLayer && this.bgLayer != undefined) {
      bgImage = this.bgLayer.querySelector('img').getAttribute('src');
    }*/
    var texture = new PIXI.Texture.fromImage(backgroundImage);
    var image = new PIXI.Sprite(texture);

    if(this.imgWidth){
      image.width=this.imgWidth
    }
    if(this.imgHeight){
      image.height=this.imgHeight
    }
    //把需要生效的图片动画加到子舞台中
    this.slidesContainer.addChild( image );
    var ticker = new PIXI.ticker.Ticker();
    ticker.autoStart = true;
    ticker.add((delta) => {
      this.backgroundImageSprite.x += this.autoPlaySpeed[0] * delta;
      this.backgroundImageSprite.y += this.autoPlaySpeed[1];
      this.renderer.render(this.stage);
    });
  }


  process(backgroundImage,width,height) {
    this.imgWidth=width
    this.imgHeight=height
    this.init(backgroundImage)
  }
}
