/**
 * Created by rockyl on 2018/8/16.
 */

import { props } from "../props";
import qietu from "./qietu";
import { getIndexFromRC, getRandomArray, getTexture } from "./utils";
import ObjectPool = engine.ObjectPool;

// let OFFSET_X;
// let OFFSET_Y;
let MAX_COL;
let MAX_ROW;
let W;
let H;
let GAP;
let GAME_TIME;
// 每张图片宽
let w;
// 每张图片高
let h;
// 图片
let picUrl

export default class GameView extends engine.Container {
  private _timer;
  private _timeCounter = 0;
  private _result = []
  private date

    

  start() {
    picUrl = props.picUrl;
    MAX_COL = props.MAX_COL;
    MAX_ROW = props.MAX_ROW;
    GAME_TIME = props.GAME_TIME;
    // OFFSET_X = props.OFFSET_X;
    // OFFSET_Y = props.OFFSET_Y;
    W = props.W;
    H = props.H;
    GAP = props.GAP;
    // 每张图片宽
    w = W / MAX_COL;
    // 每张图片高
    h = H / MAX_ROW;

    
    // if (!this.guideHole) {
    //   this.guideHole = new engine.Image();
    //   this.guideHole.source = 'asset://' + props.blockUrl;
    //   this.guideHole.mouseChildren = this.guideHole.mouseEnabled = false;
    // }

    // if (this.pictures) {
    //   for (const pic of this.pictures) {
    //     if (pic && pic.parent)
    //       pic.parent.removeChild(pic);
    //   }
    // }

    console.log('on start')
    engine.globalEvent.dispatchEvent('pictures-time-update', {
      second: this.getSecond(),
    });

    // 图片一维数组
    if(this._result.length !==0){
      this._result = []
    }

    this._result = qietu(this.picturesWrapper, picUrl, MAX_COL, MAX_ROW);
    // this.picturesWrapper.addChild(this.guideHole);

    // console.log(this.picturesWrapper)

    this.pictures = this._result[0];
    if(this.rightList !==  null){
      this.rightList = []
    }
    this.rightList = this.pictures.concat([]);
    const posList = this._result[1];
    getRandomArray(this.pictures);

    let i = 0;
    let len;
    len = this.pictures.length;


    for (; i < len; i++) {
      this.dragPic = this.pictures[i];
      this.pictures[i].addEventListener(
        engine.MouseEvent.MOUSE_DOWN,
        this.onDown,
        this
      );
      const [x, y] = posList[i];
      this.dragPic.x = x;
      this.dragPic.y = y;

    }

    this._timer = setInterval(() => {
      this.onTimer();
    }, 10)

    this.date = new Date().getTime();

  }

  onTimer() {

    let date = new Date().getTime();

    let gap = ((date - this.date) / 1000);
    this.date = date;
    // console.log(gap,"gap");

    // 以GAME_TIME为标准
    GAME_TIME -= gap;
    if(GAME_TIME < 0){
      GAME_TIME = 0;
    }
    GAME_TIME = this.afterPointTwo(GAME_TIME);
    GAME_TIME = GAME_TIME.toFixed(2);
    if (GAME_TIME < 10) {
      GAME_TIME = '0' + GAME_TIME
    }
    // console.log(GAME_TIME);


    engine.globalEvent.dispatchEvent('pictures-time-update', {
      second: this.getSecond(),
    });

    if (this.getSecond() == 0) {
      this.stop();
      engine.globalEvent.dispatchEvent('pictures-game-fail', {
        reason: 1
      });

      this.stage.removeEventListener(
        engine.MouseEvent.MOUSE_UP,
        this.stageOnUp,
        this
      );

    }
  }

  afterPointTwo(n) {

    var floatN = parseFloat(n);
    if (isNaN(floatN)) {
      return;
    }
    floatN = Math.round(floatN * 100) / 100;
    return floatN;

  }

  getSecond() {
    return GAME_TIME
  }

  stop() {
    
    GAME_TIME = props.GAME_TIME
    clearInterval(this._timer);
    let len = this.pictures.length;
    for(let i=0;i<len;i++){
      this.pictures[i].removeAllEventListener();
    }
  }

  constructor() {
    super();
    this.once(engine.Event.ADDED_TO_STAGE, this.setup, this);
  }

  //当前图片对象
  dragPic;
  // 鼠标在当前图片上的位置
  localPicX;
  localPicY;
  // 拖动的图片最开始的位置(左上角为准)
  distanceX;
  distanceY;
  // 图片中心的位置
  centerX: number;
  centerY: number;

  pictures: engine.Sprite[];

  // 点击图片时的一维数组索引
  index;
  // 计算目标图片行和列的位置
  indexI: number;
  indexJ: number;
  rightList: engine.Sprite[];

  private picturesWrapper: engine.Sprite;
  private guideHole: engine.Image;

  createRects() { }
  setup() {

    

    console.log('onSteup', props);

    const parent = new engine.Sprite();
    this.picturesWrapper = parent;
    this.addChild(parent);

    // this.picturesWrapper.x = OFFSET_X;
    // this.picturesWrapper.y = OFFSET_Y;

    // 添加按钮
    // const btn = new engine.Rect();
    // btn.width = 200;
    // btn.height = 100;
    // btn.stage.top = 1000;
    // btn.stage.left = 350;
    // btn.fillColor = 'cyan';
    // this.addChild(btn)

    // btn.addEventListener(engine.MouseEvent.CLICK,this.onClk,this)

  }

  onDown(e: engine.MouseEvent) {
    // console.log(e);

    let stageLeft = (750 - props.W) / 2
    let stageTop = (this.stage.height - props.H) / 2;

    // 创建一个图片对象接收当前位置信息
    this.dragPic = e.target;
    this.picturesWrapper.addChild(this.dragPic);


    // 鼠标的偏移量
    this.localPicX = e.localX / MAX_COL;
    this.localPicY = e.localY / MAX_ROW;

    // 最开始图片的位置
    this.distanceX = this.dragPic.x ;
    this.distanceY = this.dragPic.y;

    // 最开始点击的图片的索引值

    this.indexJ = Math.floor((this.distanceX) / (w + GAP));
    this.indexI = Math.floor((this.distanceY) / (h + GAP));
    this.index = (this.indexI) * MAX_COL + this.indexJ;


    // this.centerX = Math.floor(e.clientX / w) * w + w / 2;
    // this.centerY = Math.floor(e.clientY / h) * h + h / 2;

    this.centerX = Math.floor((e.clientX - stageLeft) / w) * w + w / 2;
    this.centerY = Math.floor((e.clientY - stageTop) / h) * h + h / 2;

    this.stage.addEventListener(
      engine.MouseEvent.MOUSE_MOVE,
      this.onMove,
      this
    );
    this.stage.addEventListener(
      engine.MouseEvent.MOUSE_UP,
      this.stageOnUp,
      this
    );

  }

  listenStageOn = 1;

  stageOnUp(e) {

    let stageLeft = (750 - props.W) / 2
    let stageTop = (this.stage.height - props.H) / 2;

    this.stage.removeEventListener(
      engine.MouseEvent.MOUSE_MOVE,
      this.onMove,
      this
    );

    this.stage.removeEventListener(
      engine.MouseEvent.MOUSE_UP,
      this.stageOnUp,
      this
    );

    // 拖动的图片的中心位置在图片之外,回到原来的位置
    if (this.centerY < stageTop || this.centerX < stageLeft) {
      this.dragPic.x = this.distanceX ;
      this.dragPic.y = this.distanceY ;
    }

    // 判断图片是否进入另一张图片的范围内
    // 要交换的图片第几行第几列
    let curJ = Math.floor(this.centerX / (w + GAP));
    let curI = Math.floor(this.centerY / (h + GAP));

    // this.picturesWrapper.addChild(this.guideHole);



    // 点击图片的位置

    if ( 0 <= curJ && curJ < (MAX_COL) && 0 <= curI && curI < (MAX_ROW)) {

      // 获取交互图片的索引值
      let index = getIndexFromRC(curI, curJ, MAX_COL);
      // console.log(index);

      //要交换的图片
      let dropPic = this.pictures[index];

      let dropPicX = dropPic.x + stageLeft;
      let dropPicy = dropPic.y + stageTop;

      dropPic.x = this.distanceX;
      dropPic.y = this.distanceY;

      this.dragPic.x = dropPicX - stageLeft;
      this.dragPic.y = dropPicy - stageTop;

      // 交换之后索引也需要交换

      const dropPicIndex = this.pictures.indexOf(dropPic);
      const dragPicIndex = this.pictures.indexOf(this.dragPic);

      this.pictures[dropPicIndex] = this.dragPic;
      this.pictures[dragPicIndex] = dropPic;

      // 图片中心还是在原来的位置
      if (dragPicIndex === dropPicIndex) {
        this.dragPic.x = this.distanceX
        this.dragPic.y = this.distanceY
      }

      let result = true;
      for (let j = 0; j < this.rightList.length; j++) {
        if (this.rightList[j] != this.pictures[j]) {
          result = false;
          break;
        }
      }

      if (result) {
        this.onSuccess();

      }
    } else {
      this.dragPic.x = this.distanceX
      this.dragPic.y = this.distanceY
    }

  }

  private onSuccess() {
    console.log('拼图成功!');
    engine.globalEvent.dispatchEvent('pictures-game-success', { time: GAME_TIME });
    this.stop();
    props.GAME_TIME *= 0.9;
    ++props.MAX_ROW ;
    ++props.MAX_COL ;

  }

  onMove(e: engine.MouseEvent) {
    // 当前图片的位置
    this.dragPic.x = e.stageX - this.localPicX - (750 - props.W) / 2;
    this.dragPic.y = e.stageY - this.localPicY - (this.stage.height - props.H) / 2;

    // 当前图片的中心位置
    this.centerX = this.dragPic.x + w / 2;
    this.centerY = this.dragPic.y + h / 2;
  }

  // onClk(e){
  //     // 重置时间
  //     this._timeCounter = 0;
  //     //重置图片顺序
  // }


}
