import { Component, ElementRef, ViewChild, OnInit, Input, OnDestroy, HostListener } from '@angular/core';

import {
  Label,
  MySprite,
  ShapeCircle,
  rotateItem,
  tweenChange,
  removeItemFromArr,
  angleToRadian,
  getPosByAngle
} from './Unit';
import { res, resAudio } from './resources';

import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';

import TWEEN from '@tweenjs/tween.js';




@Component({
  selector: 'app-play',
  templateUrl: './play.component.html',
  styleUrls: ['./play.component.css']
})
export class PlayComponent implements OnInit, OnDestroy {

  @ViewChild('canvas', { static: true }) canvas: ElementRef;
  @ViewChild('wrap', { static: true }) wrap: ElementRef;

  // 数据
  data;

  ctx;

  canvasWidth = 1280; // canvas实际宽度
  canvasHeight = 720; // canvas实际高度

  canvasBaseW = 1280; // canvas 资源预设宽度
  canvasBaseH = 720;  // canvas 资源预设高度

  mx; // 点击x坐标
  my; // 点击y坐标


  // 资源
  rawImages = new Map(res);
  rawAudios = new Map(resAudio);

  images = new Map();

  animationId: any;
  winResizeEventStream = new Subject();

  audioObj = {};

  renderArr;
  mapScale = 1;

  canvasLeft;
  canvasTop;

  saveKey = 'DF_L204';

  btn_go;

  btn_go_val;

  bg_pic;

  //转盘
  rotaryTable;

  //转盘2
  rotaryTable2;

  //阴影
  shadows = [];

  //旋转阴影
  rotate_shadow_pic;

  //选中阴影
  choic_shadow_pic;

  //发光
  light_pic;

  multiple = 2;

  temp_multiple = 0;

  //卡片半径
  cardOuterR = 90;

  //卡片内半径
  cardInerR = 70;

  maxWidth = 450;

  initRotaryTableScale = 0.1;

  first = true;

  canTouch = false;

  nextExercisesIndex = 0;

  curExercises;

  playingStatus = false;

  //练习题内容
  curContents = [];

  //练习题临时数组，用于随机取数
  tempContents = [];

  curContent;

  @HostListener('window:resize', ['$event'])
  onResize(event) {
    this.winResizeEventStream.next();
  }


  ngOnInit() {

    this.data = {};

    // 获取数据
    const getData = (<any>window).courseware.getData;
    getData((data) => {

      if (data && typeof data == 'object') {
        this.data = data;
      }
      console.log('data:', data);

      // 初始化 各事件监听
      this.initListener();

      // 若无数据 则为预览模式 需要填充一些默认数据用来显示
      this.initDefaultData();

      // 初始化 音频资源
      this.initAudio();
      // 初始化 图片资源
      this.initImg();
      // 开始预加载资源
      this.load();

    }, this.saveKey);

  }

  ngOnDestroy() {
    window['curCtx'] = null;
    window.cancelAnimationFrame(this.animationId);
  }


  load() {

    // 预加载资源
    this.loadResources().then(() => {
      window["air"].hideAirClassLoading(this.saveKey, this.data);
      this.init();
      this.update();
    });
  }


  init() {

    this.initCtx();
    this.initData();
    this.initView();

    this.playAudio('begin', false, () => {
      //this.canTouch = true;
    });
    /*
    const audio = this.audioObj['begin'];
    let duration = audio.duration * 1000;
    setTimeout(() => {
      this.canTouch = true;
    }, duration);
    */
  }

  initCtx() {
    this.canvasWidth = this.wrap.nativeElement.clientWidth;
    this.canvasHeight = this.wrap.nativeElement.clientHeight;
    this.canvas.nativeElement.width = this.wrap.nativeElement.clientWidth;
    this.canvas.nativeElement.height = this.wrap.nativeElement.clientHeight;


    this.ctx = this.canvas.nativeElement.getContext('2d');
    this.canvas.nativeElement.width = this.canvasWidth;
    this.canvas.nativeElement.height = this.canvasHeight;

    window['curCtx'] = this.ctx;
  }






  updateItem(item) {
    if (item) {
      item.update();
    }
  }

  updateArr(arr) {
    if (!arr) {
      return;
    }
    for (let i = 0; i < arr.length; i++) {
      arr[i].update(this);
    }
  }







  initListener() {

    this.winResizeEventStream
      .pipe(debounceTime(500))
      .subscribe(data => {
        this.renderAfterResize();
      });


    // ---------------------------------------------
    const setParentOffset = () => {
      const rect = this.canvas.nativeElement.getBoundingClientRect();
      this.canvasLeft = rect.left;
      this.canvasTop = rect.top;
    };
    const setMxMyByTouch = (event) => {
      if (event.touches.length <= 0) {
        return;
      }
      if (this.canvasLeft == null) {
        setParentOffset();
      }
      this.mx = event.touches[0].pageX - this.canvasLeft;
      this.my = event.touches[0].pageY - this.canvasTop;
    };

    const setMxMyByMouse = (event) => {
      this.mx = event.offsetX;
      this.my = event.offsetY;
    };
    // ---------------------------------------------


    let firstTouch = true;

    const touchDownFunc = (e) => {
      if (firstTouch) {
        firstTouch = false;
        removeMouseListener();
      }
      setMxMyByTouch(e);
      this.mapDown(e);
    };
    const touchMoveFunc = (e) => {
      setMxMyByTouch(e);
      this.mapMove(e);
    };
    const touchUpFunc = (e) => {
      setMxMyByTouch(e);
      this.mapUp(e);
    };

    const mouseDownFunc = (e) => {
      if (firstTouch) {
        firstTouch = false;
        removeTouchListener();
      }
      setMxMyByMouse(e);
      this.mapDown(e);
    };
    const mouseMoveFunc = (e) => {
      setMxMyByMouse(e);
      this.mapMove(e);
    };
    const mouseUpFunc = (e) => {
      setMxMyByMouse(e);
      this.mapUp(e);
    };


    const element = this.canvas.nativeElement;

    const addTouchListener = () => {
      element.addEventListener('touchstart', touchDownFunc);
      element.addEventListener('touchmove', touchMoveFunc);
      element.addEventListener('touchend', touchUpFunc);
      element.addEventListener('touchcancel', touchUpFunc);
    };
    const removeTouchListener = () => {
      element.removeEventListener('touchstart', touchDownFunc);
      element.removeEventListener('touchmove', touchMoveFunc);
      element.removeEventListener('touchend', touchUpFunc);
      element.removeEventListener('touchcancel', touchUpFunc);
    };

    const addMouseListener = () => {
      element.addEventListener('mousedown', mouseDownFunc);
      element.addEventListener('mousemove', mouseMoveFunc);
      element.addEventListener('mouseup', mouseUpFunc);
    };
    const removeMouseListener = () => {
      element.removeEventListener('mousedown', mouseDownFunc);
      element.removeEventListener('mousemove', mouseMoveFunc);
      element.removeEventListener('mouseup', mouseUpFunc);
    };

    addMouseListener();
    addTouchListener();
  }


  playAudio(key, now = false, callback = null) {

    const audio = this.audioObj[key];
    if (audio) {
      if (now) {
        audio.pause();
        audio.currentTime = 0;
      }

      if (callback) {
        audio.onended = () => {
          callback();
        };
      }
      audio.play();
    }
  }

  pauseAudio(key, callback = null) {

    const audio = this.audioObj[key];
    if (audio) {

      if (callback) {
        audio.onended = () => {
          callback();
        };
      }
      audio.pause();
    }
  }

  loadResources() {
    const pr = [];
    this.rawImages.forEach((value, key) => {// 预加载图片

      const p = this.preload(value)
        .then(img => {
          this.images.set(key, img);
        })
        .catch(err => console.log(err));

      pr.push(p);
    });

    this.rawAudios.forEach((value, key) => {// 预加载音频

      const a = this.preloadAudio(value)
        .then(() => {
          // this.images.set(key, img);
        })
        .catch(err => console.log(err));

      pr.push(a);
    });
    return Promise.all(pr);
  }

  preload(url) {
    return new Promise((resolve, reject) => {
      const img = new Image();
      // img.crossOrigin = "anonymous";
      img.onload = () => resolve(img);
      img.onerror = reject;
      img.src = url;
    });
  }

  preloadAudio(url) {
    return new Promise((resolve, reject) => {
      const audio = new Audio();
      audio.oncanplay = (a) => {
        resolve(a);
      };
      audio.onerror = () => {
        reject();
      };
      audio.src = url;
      audio.load();
    });
  }


  renderAfterResize() {
    this.canvasWidth = this.wrap.nativeElement.clientWidth;
    this.canvasHeight = this.wrap.nativeElement.clientHeight;
    this.init();
  }





  checkClickTarget(target) {

    const rect = target.getBoundingBox();

    if (this.checkPointInRect(this.mx, this.my, rect)) {
      return true;
    }
    return false;
  }

  getWorlRect(target) {

    let rect = target.getBoundingBox();

    if (target.parent) {

      const pRect = this.getWorlRect(target.parent);
      rect.x += pRect.x;
      rect.y += pRect.y;
    }
    return rect;
  }

  checkPointInRect(x, y, rect) {
    if (x >= rect.x && x <= rect.x + rect.width) {
      if (y >= rect.y && y <= rect.y + rect.height) {
        return true;
      }
    }
    return false;
  }





  addUrlToAudioObj(key, url = null, vlomue = 1, loop = false, callback = null) {

    const audioObj = this.audioObj;

    if (url == null) {
      url = key;
    }

    this.rawAudios.set(key, url);

    const audio = new Audio();
    audio.src = url;
    audio.load();
    audio.loop = loop;
    audio.volume = vlomue;

    audioObj[key] = audio;

    if (callback) {
      audio.onended = () => {
        callback();
      };
    }
  }

  addUrlToImages(url) {
    this.rawImages.set(url, url);
  }






  // ======================================================编写区域==========================================================================





  /**
   * 添加默认数据 便于无数据时的展示
   */
  initDefaultData() {

    if (!this.data.exercises) {

      this.data.exercises = [];

      let exercises = { contents: [] };

      for (let i = 0; i < 5; ++i) {

        let contentItem;

        if (i % 2 == 0) {
          contentItem = this.getDefaultContentItem('', 'assets/play/lion.png');
        }
        else if (i % 3 == 0) {
          contentItem = this.getDefaultContentItem('', 'assets/play/monkey.png');
        }
        else {
          contentItem = this.getDefaultContentItem('Lion', null);
        }
        console.log(contentItem);
        exercises.contents.push(contentItem);

        this.data.exercises.push(exercises);
      }
    }
  }

  /**
   * 
   * @param text 
   * @param pic_url 
   */
  getDefaultContentItem(text, pic_url) {
    let content = {
      val: text,
      pic_url: pic_url,
      audio_url: this.rawAudios.get('click')
    }

    return content;
  }

  /**
   * 添加预加载图片
   */
  initImg() {

    for (let i = 0; i < this.data.exercises.length; ++i) {

      let exercises = this.data.exercises[i];

      for (let j = 0; j < exercises.contents.length; ++j) {
        let content = exercises.contents[j];

        this.addUrlToImages(content.pic_url);
      }
    }

  }

  /**
   * 添加预加载音频
   */
  initAudio() {

    this.addUrlToAudioObj('playing', this.rawAudios.get('playing'));

    this.addUrlToAudioObj('begin', this.rawAudios.get('begin'));

    this.addUrlToAudioObj('stop', this.rawAudios.get('stop'));

    this.addUrlToAudioObj('pop-up', this.rawAudios.get('pop-up'));

    for (let i = 0; i < this.data.exercises.length; ++i) {

      let exercises = this.data.exercises[i];

      for (let j = 0; j < exercises.contents.length; ++j) {

        let content = exercises.contents[j];

        this.addUrlToAudioObj(content.audio_url);
      }
    }


  }



  /**
   * 初始化数据
   */
  initData() {

    const sx = this.canvasWidth / this.canvasBaseW;
    const sy = this.canvasHeight / this.canvasBaseH;
    const s = Math.min(sx, sy);
    this.mapScale = s;

    console.log('mapsacle:', this.mapScale);

    this.renderArr = [];

    this.curExercises = {};

    this.nextExercisesIndex = 0;

    this.curContents = [];

    this.multiple = 2;

    this.temp_multiple = 0;

    //卡片半径
    this.cardOuterR = 90;

    //卡片内半径
    this.cardInerR = 70;

    this.maxWidth = 450;

    this.initRotaryTableScale = 0.1;

    this.cardOuterR = this.cardOuterR * this.mapScale;

    this.cardInerR = this.cardInerR * this.mapScale;

    this.initRotaryTableScale = this.initRotaryTableScale * this.mapScale;

    this.maxWidth = this.maxWidth * this.mapScale;

    this.curContent = {};

    this.shadows = [];

    //产生转速倍数
    this.temp_multiple = this.multiple * (1 + Math.random());

    this.playingStatus = false;

    this.first = true;
  }



  /**
   * 初始化试图
   */
  initView() {


    this.initPic();

    this.initBottomPart();
  }

  initBottomPart() {

    const btnGo = new MySprite();
    btnGo.init(this.images.get('btn_go'));
    btnGo.x = this.canvasWidth - 100 * this.mapScale;
    btnGo.y = this.canvasHeight - 100 * this.mapScale;

    btnGo.setScaleXY(this.mapScale);

    this.renderArr.push(btnGo);

    this.btn_go = btnGo;


    let btn_go_val = new Label();
    btn_go_val.text = "Go";
    btn_go_val.textAlign = 'middle';
    btn_go_val.fontSize = 50;
    btn_go_val.fontName = "BRLNSDB";
    btn_go_val.fontColor = "#FFFFFF";

    btn_go_val.refreshSize();

    btn_go_val.x = - btn_go_val.width / 2;

    this.btn_go.addChild(btn_go_val);

    this.btn_go_val = btn_go_val;
  }

  initPic() {

    const bg_pic = new MySprite();
    bg_pic.init(this.images.get('bg'));
    bg_pic.x = this.canvasWidth / 2;
    bg_pic.y = this.canvasHeight / 2;
    bg_pic.setScaleXY(this.canvasWidth / bg_pic.width);

    this.renderArr.push(bg_pic);
    this.bg_pic = bg_pic;

    this.initRotaryTable();
  }


  /**
   * 初始化转盘
   */
  initRotaryTable() {

    const light_pic = new MySprite();
    light_pic.init(this.images.get('light'));
    light_pic.alpha = 0;
    light_pic.x = this.canvasWidth / 2;
    light_pic.y = this.canvasHeight / 2;
    light_pic.setScaleXY(this.mapScale);
    this.light_pic = light_pic;
    this.renderArr.push(light_pic);

    let rotaryTable = new ShapeCircle();

    rotaryTable.setRadius(150 * this.mapScale);

    rotaryTable.x = this.canvasWidth / 2;
    rotaryTable.y = this.canvasHeight / 2;
    rotaryTable.alpha = 0;

    this.rotaryTable = rotaryTable;

    let rotaryTable2 = new ShapeCircle();

    rotaryTable2.setRadius(150 * this.mapScale);

    rotaryTable2.x = this.canvasWidth / 2;
    rotaryTable2.y = this.canvasHeight / 2;
    rotaryTable2.alpha = 0;

    this.rotaryTable2 = rotaryTable2;

    const rotate_shadow_pic = new MySprite();
    rotate_shadow_pic.init(this.images.get('rotate_shadow'));
    rotate_shadow_pic.alpha = 0;
    rotate_shadow_pic.x = 0;
    rotate_shadow_pic.y = rotaryTable2.height / 2 + this.cardOuterR;
    this.rotate_shadow_pic = rotate_shadow_pic;
    rotaryTable2.addChild(rotate_shadow_pic);

    const choic_shadow_pic = new MySprite();
    choic_shadow_pic.init(this.images.get('choice_shadow'));
    choic_shadow_pic.alpha = 0;
    choic_shadow_pic.x = 0;
    choic_shadow_pic.y = rotaryTable2.height / 2 + this.cardOuterR;
    choic_shadow_pic.setScaleXY(0);
    this.choic_shadow_pic = choic_shadow_pic;
    rotaryTable2.addChild(choic_shadow_pic);



    this.initExercises();

    this.renderArr.push(rotaryTable2);

    this.renderArr.push(rotaryTable);

    setTimeout(() => {


      for (let i = 0; i < this.curContents.length; ++i) {

        let content = this.curContents[i];

        //由小变大
        tweenChange(content.card, { scaleX: content.initScale, scaleY: content.initScale }, 0.5, () => {
          this.canTouch = true;
        });

      }

      for (let i = 0; i < this.shadows.length; ++i) {
        let shadow = this.shadows[i];

        let scale = shadow.scale;

        tweenChange(shadow.pic, { scaleX: scale, scaleY: scale }, 0.5, () => {
          this.canTouch = true;
        });
      }
    }, 500);


  }

  initExercises() {
    if (!this.data.exercises) {
      return;
    }

    //结束整个练习则不再初始化
    if (this.nextExercisesIndex == this.data.exercises.length) {

      return;
    }

    this.curExercises = this.data.exercises[this.nextExercisesIndex];

    //循环处初始化卡片内容
    for (let i = 0; i < this.curExercises.contents.length; ++i) {

      let content = this.curExercises.contents[i];

      let tContent = { card: null, audio_url: null, card_show: null, card_choice: null };

      let contentCard = this.getContentCard(content, tContent);

      this.rotaryTable.addChild(contentCard);

      tContent.card = contentCard;
      tContent.audio_url = content.audio_url;

      this.curContents.push(tContent);

      this.tempContents.push(tContent);
    }

    //计算角度
    if (!this.curContents) {
      return;
    }

    //卡片半径
    let card_r = this.cardOuterR;

    //圆盘半径
    let rotaryTable_r = this.rotaryTable.getBoundingBox().width / 2;

    //间隔角度
    let interval_angle = Math.floor(360 / this.curContents.length);

    let max_radian = angleToRadian(interval_angle / 4);

    //计算卡片最大半径
    let max_radius = 2 * Math.sin(max_radian) * rotaryTable_r - 10 * this.mapScale;


    let scale = 1;

    //如果弦长小于卡片直径，则缩小卡片半径
    if (max_radius < card_r) {

      scale = max_radius / card_r;

      console.log('new scale:', scale);
    }

    let start_angle = 0;

    //计算坐标
    for (let i = 0; i < this.curContents.length; ++i) {

      let content = this.curContents[i];

      let pos = getPosByAngle(start_angle, rotaryTable_r);

      content.card.x = pos.x;

      content.card.y = pos.y;

      this.setShadow(content.card);


      //记录初始x坐标
      content.initX = pos.x;

      //记录初始y坐标
      content.initY = pos.y;

      content.initScale = scale;

      content.startAngle = start_angle;

      content.tableR = rotaryTable_r;

      start_angle = start_angle + interval_angle;

      content.card.setScaleXY(this.initRotaryTableScale);
    }
  }

  /**
   * 获取卡片
   * @param content 练习题内容
   */
  getContentCard(content, contentObj) {

    
    const card_bg = new ShapeCircle();

    card_bg.setRadius(this.cardOuterR);

    card_bg.alpha = 0;

    let card_scacle = 0;

    const contentCard = new MySprite();
    {
      //卡片
      contentCard.init(this.images.get('card-3x'));


      card_bg.addChild(contentCard);

      let w = contentCard.width;

      card_scacle = card_bg.width / w;

      contentCard.setScaleXY(card_scacle);

      contentObj.card_show = contentCard;
    }

    const choiceCard = new MySprite();
    {

      //卡片
      choiceCard.init(this.images.get('choice_card'));

      choiceCard.alpha = 0;

      card_bg.addChild(choiceCard);

      choiceCard.setScaleXY(card_scacle);

      contentObj.card_choice = choiceCard;
    }


    //图片存在，则渲染图片
    if (content.pic_url) {

      const content_pic = new MySprite();
      content_pic.init(this.images.get(content.pic_url));

      let w = content_pic.width;

      let h = content_pic.height;

      let d = Math.sqrt(w * w + h * h);

      content_pic.setScaleXY((contentCard.width - 75) / d);

      content_pic.x = 0;
      content_pic.y = 0;
      contentCard.addChild(content_pic);

      choiceCard.addChild(content_pic);
    }
    else {
      let content_val = new Label();
      content_val.text = content.val;
      content_val.textAlign = 'middle';
      content_val.fontSize = 50;
      content_val.fontName = "BRLNSDB";
      content_val.fontColor = "#e05e14";

      content_val.refreshSize();

      this.setFontSize(contentCard.width - 60, content_val);

      content_val.refreshSize();

      content_val.x = - content_val.getBoundingBox().width / 2;

      contentCard.addChild(content_val);
      choiceCard.addChild(content_val);
    }


    contentCard.childDepandAlpha = true;

    choiceCard.childDepandAlpha = false;

    return card_bg;
  }

  setFontSize(parWidth, label: Label) {

    if (!label) {
      return;
    }

    let w = label.width;

    let h = label.height;

    let r = Math.sqrt(w * w + h * h) / 2;

    //如果宽度超过，则缩小字体
    if (r > parWidth / 2) {

      this.shrinkFont(parWidth, label);
    }
    else {
      this.magnifyingFontSize(parWidth, label);
    }
  }

  shrinkFont(parWidth, label: Label) {
    if (!label) {
      return;
    }

    let w = label.width;

    let h = label.height;

    let r = Math.sqrt(w * w + h * h) / 2;

    //如果宽度超过，则缩小字体
    if (r > parWidth / 2) {

      let fontSize = label.fontSize;

      fontSize = fontSize - 2;

      label.fontSize = fontSize;

      label.refreshSize();


      this.shrinkFont(parWidth, label);

    }
  }

  magnifyingFontSize(parWidth, label: Label) {

    if (!label) {
      return;
    }

    let w = label.width;

    let h = label.height;

    let r = Math.sqrt(w * w + h * h) / 2;

    //如果宽度超过，则缩小字体
    if (r < parWidth / 2) {

      let fontSize = label.fontSize;

      fontSize = fontSize + 2;

      label.fontSize = fontSize;

      label.refreshSize();


      this.setFontSize(parWidth, label);

    }
  }


  /**
   * 设置阴影
   * @param itemPic 
   */
  setShadow(itemPic) {
    if (!itemPic) {
      return;
    }


    let y = itemPic.y;

    //console.log('card ', itemPic);

    //设置阴影
    if (y > -30) {

      const shadow_pic = new MySprite();
      shadow_pic.init(this.images.get('shadow'));


      shadow_pic.x = itemPic.x;
      shadow_pic.y = itemPic.y + itemPic.getBoundingBox().height / 2;

      this.rotaryTable2.addChild(shadow_pic);

      let scale = itemPic.getBoundingBox().width / shadow_pic.width;

      shadow_pic.setScaleXY(this.initRotaryTableScale);

      this.shadows.push({ pic: shadow_pic, scale: scale });
    }
  }


  /**
   * 设置阴影
   * @param itemPic 
   */
  setShadow2(x, y, w, h) {

    //设置阴影
    if (y > -30) {

      const shadow_pic = new MySprite();
      shadow_pic.init(this.images.get('shadow'));


      shadow_pic.x = x
      shadow_pic.y = y + h / 2;

      this.rotaryTable2.addChild(shadow_pic);

      let scale = w / shadow_pic.width;

      shadow_pic.setScaleXY(scale);

      this.shadows.push({ pic: shadow_pic, scale: scale });
    }
  }

  mapDown(event) {

    if (!this.canTouch) {
      return;
    }

    if (!this.playingStatus && this.checkClickTarget(this.btn_go)) {
      this.initGame();
      return;
    }

    if (this.curContent && this.curContent.card) {

      if (this.checkClickTarget(this.curContent.card)) {
        this.playAudio(this.curContent.audio_url);
      }

    }

  }

  mapMove(event) {

  }

  mapUp(event) {

  }



  update() {

    // ----------------------------------------------------------
    this.animationId = window.requestAnimationFrame(this.update.bind(this));
    // 清除画布内容
    this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
    // tween 更新动画
    TWEEN.update();
    // ----------------------------------------------------------



    this.updateArr(this.renderArr);


  }

  resetGame() {

    this.rotate_shadow_pic.alpha = 0;

    this.choic_shadow_pic.alpha = 0;

    this.curContent.card_choice.alpha = 0;

    this.choic_shadow_pic.setScaleXY(0);

    //产生转速倍数
    this.temp_multiple = this.multiple * (1 + Math.random());

    //当前内容存在，则旋转回去
    if (this.curContent) {


      //旋转
      let card_rotation = this.curContent.card.rotation;

      let residue_rotation = card_rotation % 360;

      rotateItem(this.curContent.card, 360 - residue_rotation, 0.5, () => {
        this.curContent.card.rotation = 0;
      });

      //由大变小
      tweenChange(this.curContent.card, { scaleX: this.initRotaryTableScale, scaleY: this.initRotaryTableScale }, 0.5);

      //回到原始位置
      tweenChange(this.curContent.card, { x: this.curContent.initX, y: this.curContent.initY }, 0.5, () => {
        reset();
      });
    }

    const reset = () => {
      this.pauseAudio(this.curContent.audio_url);

      //重置旋转角度
      this.rotaryTable.rotation = 0;

      //重置音频
      const audio = this.audioObj[this.curContent.audio_url];
      if (audio) {
        audio.currentTime = 0;
      }

      //显示阴影
      for (let i = 0; i < this.shadows.length; ++i) {
        this.shadows[i].alpha = 1;

      }

      this.light_pic.alpha = 0;

      //卡片恢复原状
      for (let i = 0; i < this.curContents.length; ++i) {

        let t_content = this.curContents[i];

        //旋转角度重置
        t_content.card.rotation = 0;

        t_content.card.alpha = 1;

        t_content.card.x = t_content.initX;

        t_content.card.y = t_content.initY;

        //设置初始大小
        t_content.card.setScaleXY(this.initRotaryTableScale);
      }

      //阴影恢复原状
      for (let i = 0; i < this.shadows.length; ++i) {
        this.rotaryTable2.removeChild(this.shadows[i].pic);
      }

      this.shadows = [];

      //临时数组为空，则重新设置数据
      if (!this.tempContents || this.tempContents.length == 0) {
        console.log('reset temp contntes');
        for (let i = 0; i < this.curContents.length; ++i) {
          this.tempContents.push(this.curContents[i]);
        }
      }
    }
  }

  initGame() {

    this.playingStatus = true;



    if (this.first) {

      this.first = false;
      this.playGame();
    }
    else {

      this.resetGame();

      for (let i = 0; i < this.curContents.length; ++i) {

        let content = this.curContents[i];

        //由小变大
        tweenChange(content.card, { scaleX: content.initScale, scaleY: content.initScale }, 0.5, () => {

          if (i == this.curContents.length - 1) {
            this.canTouch = true;
            this.playGame();
          }
        });

      }

      for (let i = 0; i < this.shadows.length; ++i) {
        let shadow = this.shadows[i];

        let scale = shadow.scale;

        tweenChange(shadow.pic, { scaleX: scale, scaleY: scale }, 0.5);
      }

    }

  }

  playGame() {
    this.playAudio('playing', false, () => {


    });

    this.setBtnGoText("· · ·");

    //音频长度
    const audio = this.audioObj['playing'];
    let duration = audio.duration;

    let angle = duration * 20 * this.temp_multiple;

    //隐藏小卡片阴影
    for (let i = 0; i < this.shadows.length; ++i) {
      this.shadows[i].pic.alpha = 0;

    }

    //显示旋转阴影
    this.rotate_shadow_pic.alpha = 1;

    this.rotate(this.rotaryTable, angle, duration, () => {

      this.rotate_shadow_pic.alpha = 0;

      //设置阴影
      for (let i = 0; i < this.curContents.length; ++i) {

        let content = this.curContents[i];

        //this.setShadow(content.card);

        //console.log('content startAngle', content.startAngle);

        //转动角度
        let rotation = this.rotaryTable.rotation;

        let newStartAngle = content.startAngle - rotation;

        console.log('rotation', rotation, 'content startAngle', content.startAngle, 'new content startAngle', newStartAngle);

        let pos = getPosByAngle(newStartAngle, content.tableR);

        //console.log('old x', content.initX, 'old y', content.initY);
        //console.log('pos', pos);

        this.setShadow2(pos.x, pos.y, content.card.getBoundingBox().width, content.card.getBoundingBox().height);
      }


      //显示阴影
      for (let i = 0; i < this.shadows.length; ++i) {

        let shadow = this.shadows[i];
        shadow.pic.setScaleXY(shadow.scale);
      }

      this.curContent = this.getRandomItemFromArr(this.tempContents);

      removeItemFromArr(this.tempContents, this.curContent);

      this.curContent.card_choice.alpha = 1;
      //this.curContent.card_show.alpha = 0;


      //抽取卡片
      this.drawCard();

    })

  }

  rotate(item, angle, duration, callback = null, easying = null) {

    //console.log('duration', duration);
    if (duration <= 0) {

      if (callback) {
        callback();
      }

      return;
    }

    let time = 0.1;

    if (duration < time) {
      time = duration;
    }

    let t_angle = angle % 360;

    item.rotation = t_angle;

    t_angle = t_angle + duration * 20 * this.temp_multiple;

    rotateItem(item, t_angle, time, () => {


      this.rotate(item, t_angle, duration - time, callback);

    });

  }

  /**
   * 抽取卡片
   */
  drawCard() {



    this.playAudio('pop-up');

    //新坐标
    let x = this.canvasWidth / 2;

    //新坐标
    let y = this.canvasHeight / 2;

    //调整位置
    this.rotaryTable.removeChild(this.curContent.card);
    this.rotaryTable.addChild(this.curContent.card);

    let scaleX = this.curContent.card.scaleX;


    let scale = this.maxWidth / this.curContent.card.width;

    console.log('rotaryTable rotation', this.rotaryTable.rotation);
    //由小变大
    tweenChange(this.curContent.card, { scaleX: scale, scaleY: scale }, 0.5, () => {

      //console.log('children',this.curContent.card.children);

      //隐藏阴影
      for (let i = 0; i < this.shadows.length; ++i) {
        this.shadows[i].pic.alpha = 0;
      }

      //隐藏其它的卡片
      for (let i = 0; i < this.curContents.length; ++i) {

        if (this.curContents[i] != this.curContent) {
          this.curContents[i].card.alpha = 0;
          this.curContents[i].card.setScaleXY(0);
        }
      }

      //console.log('rotaryTable rotation', this.rotaryTable.rotation);

      console.log('cur card rotation', this.curContent.card.rotation);


    });

    this.choic_shadow_pic.alpha = 1;
    tweenChange(this.choic_shadow_pic, { scaleX: this.mapScale, scaleY: this.mapScale }, 0.5);

    //移动新位置
    tweenChange(this.curContent.card, { x: 0, y: 0 }, 0.5, () => {
      this.light_pic.alpha = 1;

      this.rotateLight();

      this.playingStatus = false;

      this.setBtnGoText("GO");
    });


    //旋转
    let table_rotation = this.rotaryTable.rotation;

    let residue_rotation = table_rotation % 360;

    rotateItem(this.curContent.card, 360 - residue_rotation, 0.5, () => {
      this.playAudio('stop', false, () => {

      });
    });
  }

  /**
   * 灯光旋转
   */
  rotateLight() {
    rotateItem(this.light_pic, 360, 10, () => {
      this.light_pic.rotation = 0.036;

      if (!this.playingStatus) {
        this.rotateLight();
      }

    });
  }

  getRandomItemFromArr(arr) {

    if (!arr) {
      return;
    }

    let length = arr.length;

    let index = Math.ceil(Math.random() * 100000000) % length;

    return arr[index];
  }

  setBtnGoText(text) {
    this.btn_go_val.text = text;
    this.btn_go_val.refreshSize();
    this.btn_go_val.x = -this.btn_go_val.width / 2;
  }
}
