'use strict';

import React, { Component } from 'react';

import API from '../../api/index.js';

import './canvasScene.less';

import { GDiapatcher } from './GDiapatcher.js';

import matter,{ Engine,Runner,Render,Events,Mouse,World,Composite } from 'matter'

import { RES_PATH } from '../../../sparkrc';
//引擎sdk   <script src="//yun.duiba.com.cn/db_games/libs0924/fyge2014.min2d.js" crossorigin="anonymous"></script>
export default class CanvasScene extends Component {
  /**
   * 
   * @param {*} props
   */
  constructor(props) {
    super(props);
    this.canvasRef = React.createRef();
  }
  componentDidMount() {
    // 初始化fyge
    this.initFyge()
    // 初始化物理引擎
    this.initMatter()
    //循环 更新帧
    const self = this;
    (function loop() {
      FYGE.Tween.flush()
      self.stage.flush();
      self.requestID = window.requestAnimationFrame(loop);
    })()
  }

  /**
   * 初始化fyge
   */
  initFyge() {
    var canvas = this.canvasRef.current;
    //canvas画布实际尺寸，
    canvas.width = document.body.clientWidth * (window.devicePixelRatio || 1)
    canvas.height = document.body.clientHeight * (window.devicePixelRatio || 1)
    //建舞台
    var stage = new FYGE.Stage(
      canvas,
      750,//设计宽度，按设计搞给的就行
      1624,//设计高度
      document.body.clientWidth,//显示宽度
      document.body.clientHeight,//显示高度
      FYGE.RENDERER_TYPE.CANVAS,
      false//舞台是否居中，false左上置顶，true小于1624的视窗会上下平均裁切
    );
    //鼠标事件
    var mouseEvent = stage.onMouseEvent.bind(stage);
    canvas.addEventListener("touchstart", mouseEvent, false);
    canvas.addEventListener('touchmove', mouseEvent, false);
    canvas.addEventListener('touchend', mouseEvent, false);
    //stage初始化
    stage.addEventListener(FYGE.Event.INIT_STAGE, this.initScene, this)
    //挂舞台指向
    this.stage = stage;
  }

  /**
   * 初始化物理引擎
   */
  initMatter() {
    console.log('matter-js',matter)
    // 创建引擎
    var engine = this.engine =  Engine.create()

    // 设置重力
    this.engine.gravity.y = 2
    this.engine.gravity.x = 0.0

    // 引擎内通过物理合成器已经创建了 世界
    this.world = engine.world;
    // 拿到物理合成器
    this.composite = Composite
    // 将引擎创建的世界加入合成器内
    this.composite.add(this.world, [])


    // 每帧更新后
  Events.on(engine, 'afterUpdate', function () {
    console.log('每帧更新后')
  });
  }

  update() {
    Engine.update(this.engine, 1000 / 60)
    super.update()
  }

  async initScene() {
    var stage = this.stage;
    //添加个背景矢量图
    stage.addChild(new FYGE.Graphics())
      .beginFill(0x000000, 0.7)
      .drawRect(0, 0, 750, 1624)
      .endFill()


    //单图纹理
    var texture = await new Promise((r) => {
      FYGE.GlobalLoader.loadImage((s, image) => {
        r(FYGE.Texture.fromImage(image))
      }, RES_PATH + "aa.png")
    })
    //纹理图片
    var sp = stage.addChild(new FYGE.Sprite(texture))
      .addEventListener(FYGE.MouseEvent.CLICK, () => { console.log("点击了") }, this)
    sp.position.set(200, 500);//位置
    sp.scale.set(0.5, 0.5)//缩放
    sp.anchorTexture.set(0.5, 0.5)//贴图锚点，改变初始坐标，0到1
    //遮罩
    var mask = stage.addChild(new FYGE.Graphics())
      .beginFill(0x000000)
      .drawRect(100, 500, 400, 300)
      .endFill()
    sp.mask = mask;
    //来个动画
    FYGE.Tween.get(sp)
      .to({ rotation: 360 }, 5000)
      .to({ scaleX: 1.1, scaleY: 1.1 }, 3000)
      .to({ scaleX: 1, scaleY: 1 }, 300)
      .to({ x: 400 }, 1000)
      .call(() => { console.log("动画结束") })

    //异步渲染网络图片
    stage.addChild(FYGE.Sprite.fromUrl("https://img.alicdn.com/imgextra/i4/2275046294/O1CN01avEmL01wMhS5Wxd63_!!2275046294-2-miniprogram.png"))
      .position.set(300, 700)
    //文本
    var text = stage.addChild(new FYGE.TextField())
    text.size = 30//字号
    text.text = "亲吻青蛙撒大"//内容
    text.textAlign = FYGE.TEXT_ALIGN.CENTER//居中
    text.textWidth = 400//居中需要设置文本固定宽度才有效
    text.position.set(100, 1000)
    var a = { x: 0 }
    FYGE.Tween.get(a, {
      onChange: () => {//缓动改变时监听
        text.text = "亲吻青蛙撒大" + Math.round(a.x)
      }
    })
      .to({ x: 10000 }, 100000)

    //位图文本chapterNum0
    var textures = await new Promise((r) => {
      var t = {};
      let count = 0;
      for (var i = 0; i < 10; i++) {
        let c = i;
        FYGE.GlobalLoader.loadImage((s, image) => {
          t["" + c] = FYGE.Texture.fromImage(image);
          if (++count == 10) r(t)
        }, RES_PATH + "chapterNum" + c + ".png")
      }
    })
    console.log(textures)
    var bitmapText = stage.addChild(new FYGE.BitmapText(textures))
    bitmapText.text = "12345"
    bitmapText.x = 300
    bitmapText.y = 200
    bitmapText.textAlign = "center"
    bitmapText.verticalAlign = "middle"
    bitmapText.gap = -6
    var b = { x: 0 }
    console.log(bitmapText)
    // FYGE.Tween.get(b, {
    //     onChange: () => {//缓动改变时监听
    //         bitmapText.text = "" + Math.round(b.x)
    //     }
    // })
    //     .to({ x: 10000 }, 100000)


    //帧动画
    var texArr = []//需要纹理的数组
    for (var i = 0; i <= 15; i++) texArr.push(FYGE.Texture.fromUrl(RES_PATH + "hor_ele1_" + i + ".png"));
    for (var i = 14; i >= 1; i--) texArr.push(FYGE.Texture.fromUrl(RES_PATH + "hor_ele1_" + i + ".png"));//反方向
    var frameAni = stage.addChild(new FYGE.FrameAni(texArr))
    frameAni.position.set(200, 900)
    frameAni.mouseEnable = frameAni.mouseChildren = false;//鼠标事件去掉，可穿透
    frameAni.play(0)//循环播放

    //svga动画 sdk  <script src="//yun.duiba.com.cn/db_games/libs0924/svgaParser.minWeb.js" crossorigin="anonymous"></script>
    SvgaParser.loadSvga(RES_PATH + "小贱成年常态.svga", (v) => {
      stage.addChild(new FYGE.MovieClip(v)).y -= 600
    })
    //lottie动画（文件全）
    FYGE.GlobalLoader.loadJson((s, json) => {
      var l = stage.addChild(new FYGE.Lottie(json))
      l.play()
      l.x += 200
    }, RES_PATH + "click_action_11.json")
    //lottie转svga播放
    FYGE.GlobalLoader.loadJson((s, json) => {
      console.log(Date.now())
      var m = stage.addChild(new FYGE.MovieClip(FYGE.lottieToSvgaData(json)))
      console.log(Date.now())
      m.mouseChildren = m.mouseEnable = false;
      m.lockStep = true;//帧率60除不尽的，只能用这个
      m.startAniRange(undefined, undefined, 2, () => {
        stage.removeChild(m)
      })
    }, RES_PATH + "yaoqinghan_tianmao.json")



    //按钮
    stage.addChild(new FYGE.Button(texture))
      .addEventListener(FYGE.MouseEvent.CLICK, () => { console.log("点击了按钮") }, this)
      .position.set(0, 1100)
    //滚动视图
    var scroll = stage.addChild(new FYGE.ScrollPage(640, 656, 100, true, false))
    scroll.position.set(500, 1100)
    scroll.view.addChild(new FYGE.Sprite(texture))//在view里面添加
    scroll.maxDistance = 1000
    setTimeout(() => { scroll.scrollTo(200, 2000) }, 2000)

    //滚动列表
    var list = new FYGE.ScrollList(class extends FYGE.Sprite {
      constructor() {
        super()
        this.txt = new FYGE.TextField();
        this.txt.size = 50;
        this.txt.fillColor = "#ff0000";
        this.addChild(this.txt)
      }
      initData(id, data) {
        if (id < 0 || !data) return
        this.txt.text = data + ""
      }
    }
      , 100, 60, 100, 400, true)
    list.x = 100;
    list.y = 300;
    list.updateData([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], true)//更新数据，true覆盖原先数据
    stage.addChild(list);


    //shape
    // var s = stage.addChild(new FYGE.Shape())
    // s.beginFill(0, 0.7)
    // s.moveTo(0, 0);
    // s.lineTo(0, 1624);
    // s.lineTo(750, 1624);
    // s.lineTo(750, 0);
    // s.lineTo(0, 0);
    // s.moveTo(300, 300)
    // s.drawRoundedRect(300, 100, 200, 100, 1111)
    // s.endFill()
    //画线
    var s = stage.addChild(new FYGE.Shape())
    s.beginStroke(0, 3)
    s.moveTo(10, 10);
    s.lineTo(10, 500);
    s.lineTo(200, 500);
    s.lineTo(200, 10);
    s.lineTo(10, 10);
    s.endStroke()
  }
  jumpScene() {
    mHistory.push({ pathname: '/a' });
  }
  componentWillUnmount = () => {
    //有
    GDiapatcher.removeAllEventListener();
    //Tween都移除，
    FYGE.Tween.removeAllTweens()
    //计时器取消
    window.cancelAnimationFrame(this.requestID);
    //舞台销毁
    this.stage.destroy();
  }
  render() {
    return (
      <div className="canvas-box" >
        <canvas id="canvas" ref={this.canvasRef}></canvas>
      </div>
    );
  }
}

