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

import {
  Label, MyAnimation,
  MySprite, tweenChange,
  moveItem, shake, circleMove, jelly,
  randomNumber, jellyStar, jellyPl,
  showPopParticle, scaleItem, moveItemIn,
  moveItemYoyo, jellyStarYoyo, jellyStarYoyoSS, alphaItem

} 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.scss']
})
export class PlayComponent implements OnInit, OnDestroy {

   @ViewChild('canvas') canvas: ElementRef;
  @ViewChild('wrap') wrap: ElementRef;

  // 数据
  data;

  ctx;

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

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

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


  yoyoTw;
  picDefYoyo;
  picYoyo;


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

  images = new Map();
  viduos = new Map();

  animationId: any;
  winResizeEventStream = new Subject();

  audioObj = {};
  starPoint = [];  // 星星坐标
  hpStarPoint = [];
  r_w = true;     // true-正确 false-错误
  renderArr;
  mapScale = 1;
  mapScaleX = 1;
  mapScaleY = 1;
   mic_url = '';
  canvasLeft;
  canvasTop;

  saveKey = 'csm_test';

  mgStatus = false;  // 记录魔术状态 【false-未打开帽子 true-已打开帽子】
  mbAnim;       // 打开幕布动画
  mgHand;       // 魔术手
  mgMz;     // 帽子
  mgMz_d;     // 帽子 阴影
  move_Pic = false; // 正在执行动画
  mgHandStar;       // 魔术手星星
  mgHandStar1;       // 魔术手星星
  mgHandStar2;       // 魔术手星星
  mgHandStar3;       // 魔术手星星
  mgHandStar4;       // 魔术手星星
  mgPicShow_def; // 帽子中已弹出的图片背景
  mgPicShow;    // 帽子中已弹出的图片
  starArr = [];    // 星星数组
  starHPArr = [];    // 星星数组
  showPic_count = 0;
  imgArr = [];
  pic1;
  pic2;
  picW;
  picH;
  canTouch = true;

  curPic;

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


  ngOnInit() {

    this.data = {};

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

      if (data) {
        this.data = data;
      }
      // && typeof data == 'object'
      this.imgArr = 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();
  }

  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;
        return;
      }

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



  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();
      };
      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() {
    this.data.pic_url = 'assets/play/default/pic.jpg';
    /*this.data.pic_url_2 = 'assets/play/default/pic.jpg';*/
   /* if (!this.data.pic_url) {
      this.data.pic_url = 'assets/play/default/pic.jpg';
      this.data.pic_url_2 = 'assets/play/default/pic.jpg';
    }*/
  }


  /**
   * 添加预加载图片
   */
  initImg() {
    const contentObj = this.data;
    if (contentObj) {
      for (let i = 0; i < contentObj.length; i++) {
        if (contentObj[i].pic_url) {
          this.rawImages.set(contentObj[i].pic_url, contentObj[i].pic_url);
        }
      }
    }

  }

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

    // 音频资源
    this.addUrlToAudioObj(this.data.audio_url);
    this.addUrlToAudioObj(this.data.audio_url_2);

    // 音效
   //  this.addUrlToAudioObj('click', this.rawAudios.get('click'), 0.3);
    this.addUrlToAudioObj('show_a', this.rawAudios.get('show_a'), 0.3);
    this.addUrlToAudioObj('alp', this.rawAudios.get('alp'), 0.3);
    this.addUrlToAudioObj('ck', this.rawAudios.get('ck'), 1);
    this.addUrlToAudioObj('mz_1', this.rawAudios.get('mz_1'), 0.3);
    this.addUrlToAudioObj('mb_1', this.rawAudios.get('mb_1'), 0.3);

    const contentObj = this.data;
    if (contentObj) {
      for (let i = 0; i < contentObj.length; i++) {
        if (contentObj[i].audio_url) {
          this.addUrlToAudioObj(contentObj[i].audio_url, contentObj[i].audio_url, 1);
        }
      }
    }


  }



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



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

    this.mapScaleX = sx;
    this.mapScaleY = sy;

    console.log('sdfasdfkljaslkdfjlaskdjflkas'+this.mapScaleX);

    this.renderArr = [];



  }



  /**
   * 初始化试图
   */
  initView() {
    this.initPoint();
    this.addHpage();
    this.animationMb();
  }
  initPoint() {
    this.starPoint = [];
    // 物体出现星星
    const p1 = {x: this.canvasWidth / 2 + 40 * this.mapScaleX, y: this.canvasHeight / 2 - 240 * this.mapScaleY };
    const p2 = {x: this.canvasWidth / 2 + 140 * this.mapScaleX, y: this.canvasHeight / 2 - 300 * this.mapScaleY };
    const p3 = {x: this.canvasWidth / 2 - 80 * this.mapScaleX, y: this.canvasHeight / 2 - 200 * this.mapScaleY };
    const p4 = {x: this.canvasWidth / 2 - 40 * this.mapScaleX, y: this.canvasHeight / 2 - 300 * this.mapScaleY };
    const p5 = {x: this.canvasWidth / 2 + 130 * this.mapScaleX, y: this.canvasHeight / 2 - 40 * this.mapScaleY };
    const p6 = {x: this.canvasWidth / 2 - 110 * this.mapScaleX, y: this.canvasHeight / 2 - 40 * this.mapScaleY };
    const p7 = {x: this.canvasWidth / 2 - 200 * this.mapScaleX, y: this.canvasHeight / 2 - 150 * this.mapScaleY };
    const p8 = {x: this.canvasWidth / 2 - 260 * this.mapScaleX, y: this.canvasHeight / 2 - 80 * this.mapScaleY };
    const p9 = {x: this.canvasWidth / 2 - 220 * this.mapScaleX, y: this.canvasHeight / 2 + 20 * this.mapScaleY };
    const p10 = {x: this.canvasWidth / 2 + 240 * this.mapScaleX, y: this.canvasHeight / 2 - 150 * this.mapScaleY };
    const p11 = {x: this.canvasWidth / 2 + 140 * this.mapScaleX, y: this.canvasHeight / 2 - 150 * this.mapScaleY };

    this.starPoint.push(p1);
    this.starPoint.push(p2);
    this.starPoint.push(p6);
    this.starPoint.push(p7);
    this.starPoint.push(p8);
    this.starPoint.push(p9);
    this.starPoint.push(p10);
    this.starPoint.push(p11);

    // 幕布拉开前出现星星
    const hp1 = {x: this.canvasWidth / 2 + 40 * this.mapScale, y: this.canvasHeight / 2 - 240 * this.mapScale };
    const hp2 = {x: this.canvasWidth / 2 + 300 * this.mapScale, y: this.canvasHeight / 2 - 230 * this.mapScale };
    const hp3 = {x: this.canvasWidth / 2 + 220 * this.mapScale, y: this.canvasHeight / 2 - 150 * this.mapScale };
    const hp4 = {x: this.canvasWidth / 2 + 340 * this.mapScale, y: this.canvasHeight / 2 };
    const hp5 = {x: this.canvasWidth / 2 + 260 * this.mapScale, y: this.canvasHeight / 2 + 140 * this.mapScale };
    const hp6 = {x: this.canvasWidth / 2 - 110 * this.mapScale, y: this.canvasHeight / 2 - 40 * this.mapScale };
    const hp7 = {x: this.canvasWidth / 2 - 200 * this.mapScale, y: this.canvasHeight / 2 - 150 * this.mapScale };
    const hp8 = {x: this.canvasWidth / 2 - 260 * this.mapScale, y: this.canvasHeight / 2 - 80 * this.mapScale };
    const hp9 = {x: this.canvasWidth / 2 - 320 * this.mapScale, y: this.canvasHeight / 2 + 20 * this.mapScale };
    const hp10 = {x: this.canvasWidth / 2 - 380 * this.mapScale, y: this.canvasHeight / 2 + 150 * this.mapScale };
    const hp11 = {x: this.canvasWidth / 2 - 140 * this.mapScale, y: this.canvasHeight / 2 + 220 * this.mapScale };
    const hp12 = {x: this.canvasWidth / 2 - 140 * this.mapScale, y: this.canvasHeight / 2 + 300 * this.mapScale };
    const hp13 = {x: this.canvasWidth / 2 - 80 * this.mapScale, y: this.canvasHeight / 2 - 200 * this.mapScale };
    const hp14 = {x: this.canvasWidth / 2 - 40 * this.mapScale, y: this.canvasHeight / 2 - 300 * this.mapScale };
    const hp15 = {x: this.canvasWidth / 2 + 130 * this.mapScale, y: this.canvasHeight / 2 - 40 * this.mapScale };
    const hp16 = {x: this.canvasWidth / 2 - 110 * this.mapScale, y: this.canvasHeight / 2 - 40 * this.mapScale };
    const hp17 = {x: this.canvasWidth / 2 - 200 * this.mapScale, y: this.canvasHeight / 2 - 150 * this.mapScale };
    const hp18 = {x: this.canvasWidth / 2 - 260 * this.mapScale, y: this.canvasHeight / 2 - 80 * this.mapScale };
    const hp19 = {x: this.canvasWidth / 2 - 220 * this.mapScale, y: this.canvasHeight / 2 + 20 * this.mapScale };
    const hp20 = {x: this.canvasWidth / 2 - 220 * this.mapScale, y: this.canvasHeight / 2 + 20 * this.mapScale };
    this.hpStarPoint.push(hp1);
    this.hpStarPoint.push(hp2);
    this.hpStarPoint.push(hp3);
    this.hpStarPoint.push(hp4);
    this.hpStarPoint.push(hp5);
    this.hpStarPoint.push(hp6);
    this.hpStarPoint.push(hp7);
    this.hpStarPoint.push(hp8);
    this.hpStarPoint.push(hp9);
    this.hpStarPoint.push(hp10);
    this.hpStarPoint.push(hp11);
    this.hpStarPoint.push(hp12); return;
    this.hpStarPoint.push(hp13);
    this.hpStarPoint.push(hp14);
    this.hpStarPoint.push(hp15);
    this.hpStarPoint.push(hp16);
    this.hpStarPoint.push(hp17);
    this.hpStarPoint.push(hp18);
    this.hpStarPoint.push(hp19);
    this.hpStarPoint.push(hp20);


  }
  // 添加幕布
  animationMb() {
    if (this.mic_url) {
      this.playAudio(this.mic_url, true);
    }
    this.picW = 265;
    this.picH = 265;
    this.mgStatus = false;
    this.move_Pic = true;
    this.showPic_count = 0;
    const mbAni = new MyAnimation();
    for (let i = 1 ; i <= 8 ; i++) {
      const mbImg = this.images.get('mb_' + i);
      console.log(mbImg);
      mbAni.addFrameByImg(mbImg);
    }
    mbAni.delayPerUnit = 0.01;

    mbAni.x = this.canvasWidth / 2;
    mbAni.y = this.canvasHeight / 2;
    mbAni.scaleX = this.canvasWidth / mbAni.width;
    mbAni.scaleY = this.canvasHeight / mbAni.height;
    this.mbAnim = mbAni;
    this.mbAnim.playEndFunc = () => {
      this.playAudio('mz_1');
      // 显示帽子&阴影&魔术手
      moveItem(this.mgMz, this.canvasWidth / 2, this.canvasHeight / 2 + 150 * this.mapScaleY, 1, () =>  {
          tweenChange(this.mgMz_d, {alpha: 1}, 0.5);
          tweenChange(this.mgHand, {alpha: 1}, 0.5, () => {
            this.showOrAlpStar(1);
            this.renderArr.push(this.mgPicShow_def);
            if (this.mgPicShow) {
              this.renderArr.push(this.mgPicShow);
            }
          this.move_Pic = false;
          this.youyouItem(this.mgHand);
        });
        jelly(this.mgMz, 0.5 );
      }, TWEEN.Easing.Elastic.InOut);
    };
    // this.mbAnim.play();
    this.renderArr.push(mbAni);
    this.homePStar();
    this.playAudio( 'mb_1');
    setTimeout( () => {
      this.mbAnim.play();
    }, 1000);

  }
  // 主界面
  addHpage() {
    // 首页
    const hpImg = new MySprite();
    hpImg.init(this.images.get('hpg'));
    hpImg.x = this.canvasWidth / 2;
    hpImg.y = this.canvasHeight / 2;
    hpImg.scaleX = this.canvasWidth / hpImg.width;
    hpImg.scaleY = this.canvasHeight / hpImg.height;
    this.renderArr.push(hpImg);
    // 帽子
    this.mgMz = new MySprite();
    this.mgMz.init(this.images.get('mz_3'));
    this.mgMz.x = this.canvasWidth / 2;
    this.mgMz.y = - this.mgMz.height / 2;

    this.mgMz_d = new MySprite();
    this.mgMz_d.init(this.images.get('mz_d'));
    this.mgMz_d.alpha = 0;
    this.mgMz_d.setScaleXY(this.mapScale);
    this.mgMz_d.x = this.canvasWidth / 2;
    this.mgMz_d.y = this.canvasHeight / 2 + 130 * this.mapScaleY + this.mgMz.height * this.mapScale / 2;
     this.mgMz.setScaleXY(this.mapScale);
    this.renderArr.push(this.mgMz_d);

    this.renderArr.push(this.mgMz);
    // 手
    this.mgHand = new MySprite();
    this.mgHand.init(this.images.get('invalid-name_8'));
    this.mgHand.x = this.canvasWidth / 2 + 250 * this.mapScaleX ;
    this.mgHand.y = this.canvasHeight / 2 + 140 * this.mapScaleY;
    this.mgHand.scaleX = 0.5 * this.mapScale;
    this.mgHand.scaleY = 0.5 * this.mapScale;
    this.mgHand.alpha = 0;
    this.renderArr.push(this.mgHand);

    this.mgHandStar = new MySprite();
    this.mgHandStar.init(this.images.get('星星5'));
    this.mgHandStar.alpha = 0;
    this.mgHandStar.x = this.mgHand.x - this.mgHand.width / 2;
    this.mgHandStar.y = this.mgHand.y - this.mgHand.height / 2;
    this.renderArr.push(this.mgHandStar);

    // 弹出图片
    this.mgPicShow_def = new MySprite();
    this.mgPicShow_def.alpha = 0;
    this.mgPicShow_def.init(this.images.get("def_k"));
    this.mgPicShow_def.x = this.canvasWidth / 2 + 4 * this.mapScale;
    this.mgPicShow_def.y = this.canvasHeight / 2 + 30 * this.mapScale;
    this.mgPicShow_def.setScaleXY(0.5 * this.mapScale);


    this.mgPicShow = new MySprite();
    this.mgPicShow.x = this.canvasWidth / 2 + 2 * this.mapScale;
    this.mgPicShow.y = this.canvasHeight / 2 + 30 * this.mapScale;
    this.renderArr.push(this.mgPicShow);
  }

  // 魔术棒星星
  mgStartAllShow() {
    tweenChange(this.mgHandStar, {alpha: 1}, 0.5, () => {

    });
    tweenChange(this.mgHandStar1, {alpha: 0.7}, 0.5, () => {

    });
    tweenChange(this.mgHandStar2, {alpha: 0.5}, 0.5, () => {

    });
    tweenChange(this.mgHandStar3, {alpha: 0.7}, 0.5, () => {

    });
    tweenChange(this.mgHandStar4, {alpha: 0.5}, 0.5, () => {
    });
  }

  lastPage() {

    if (this.curPic == this.pic1) {
      return;
    }

    this.canTouch = false;

    const moveLen = this.canvasWidth;
    tweenChange(this.pic1, {x: this.pic1.x + moveLen}, 1);
    tweenChange(this.pic2, {x: this.pic2.x + moveLen}, 1, () => {
      this.canTouch = true;
      this.curPic = this.pic1;
    });
  }

  pic1Clicked() {
    this.playAudio(this.data.audio_url);
  }

  pic2Clicked() {
    this.playAudio(this.data.audio_url_2);
  }





  mapDown(event) {

    if (!this.canTouch) {
      return;
    }

    // 点击魔术手
    if ( this.checkClickTarget(this.mgHand) ) {
      if (this.move_Pic) {
        return;
      }
      this.move_Pic = true;
      if (!this.mgStatus) {
        this.playAudio('ck');
        this.mgHand.y = this.canvasHeight / 2 + 120 * this.mapScale;
        const  xx = this.mgHand.x;
        const yy = this.mgHand.y;
        // 晃动魔术棒
        tweenChange(this.mgHand, {x: this.mgHand.x - 200, y: this.mgHand.y}, 1,
          () => {
            tweenChange(this.mgHand, {x: this.mgHand.x + 200, y: this.mgHand.y}, 0.5,
              () => {
                this.showPic();
              },
              null,
              (item) => {
                const r = 100;
                let x = r - (xx - item.x);
                if (x < 0) {
                  x = (xx - item.x) - r;
                }
                let y0 = (Math.pow(r, 2) - Math.pow(x, 2));
                if (y0 <= 0) {
                  y0 = 0;
                }
                item.y = yy - Math.sqrt(y0);
                const st1 = new MySprite();
                st1.init(this.images.get('星星4'));
                st1.x = item.x - item.width * this.mapScale / 4 + randomNumber(17, 22) * randomNumber(0, 3);
                st1.y = item.y - item.height * this.mapScale / 4 - randomNumber(7, 12) * randomNumber(0, 3);
                this.renderArr.push(st1);
                tweenChange(st1, {alpha: 0}, 0.3);
              });
          },
          null,
          (item) => {
            const r = 100 ;
            let x = r - (xx - item.x);
            if (x < 0) {
              x = (xx - item.x) - r;
            }
            let y0 = (Math.pow(r, 2) - Math.pow(x, 2));
            if (y0 <= 0) {
              y0 = 0;
            }
            item.y = yy + Math.sqrt(y0);
            const st1 = new MySprite();
            st1.init(this.images.get('星星4'));
            st1.x = item.x - item.width * this.mapScale / 4 + randomNumber(17, 22) * randomNumber(0, 3);
            st1.y = item.y - item.height * this.mapScale / 4 - randomNumber(7, 12) * randomNumber(0, 3);
            this.renderArr.push(st1);
            tweenChange(st1, {alpha: 0}, 0.3);
          });
      } else {
        if (this.mic_url) {
          this.playAudio(this.mic_url, true);
        }
        this.playAudio('alp');
        const def = {
          alpha: 0,
          x: this.canvasWidth / 2 + 4 * this.mapScale,
          y: this.canvasHeight / 2 + 30 * this.mapScale,
          scaleX: 0.2 * this.mapScale ,
          scaleY: 0.2 * this.mapScale
        };
        tweenChange(this.mgPicShow_def, def, 0.5);
        const sx = this.picW / this.mgPicShow.width;
        const sy = this.picH / this.mgPicShow.height;
        const s = Math.min(sx, sy);
        const show = {
          x: this.canvasWidth / 2,
          y: this.canvasHeight / 2 + 30 * this.mapScale,
          alpha: 0,
          scaleX: 0.2 * s * this.mapScale,
          scaleY: 0.2 * s * this.mapScale,
        };
        tweenChange(this.mgPicShow, show, 0.5);

        const hd = {
          x: this.canvasWidth / 2 + 250 * this.mapScaleX,
          y: this.canvasHeight / 2 + 130 * this.mapScaleY
        };
        tweenChange(this.mgHand, hd, 0.5, () => {
          this.youyouItem(this.mgHand);
          this.move_Pic = false;
        }, null, (item) => {
          const st1 = new MySprite();
          st1.init(this.images.get('星星4'));
          st1.x = item.x - item.width * this.mapScale / 4 ;
          st1.y = item.y - item.height * this.mapScale / 4;
          this.renderArr.push(st1);
          tweenChange(st1, {alpha: 0}, 0.3, () => {

          });
        });
      }
      this.mgStatus = !this.mgStatus;
    }
  }
  // 物体出现
  showPic() {
/*    if (this.starPoint == null || this.starPoint.length < 1) {
      this.initPoint();
    }*/
    let sct = 0;
    let sct1 = 0;
    if (this.starPoint != null && this.starPoint.length > 0) {
      for ( let i = 0; i < this.starPoint.length; i++ ) {
        this.starArr[i].alpha = 0;
        this.starArr[i].init(this.images.get('星星' + randomNumber(2, 6)));
        tweenChange(this.starArr[i], {alpha: 1}, randomNumber(3, 13) / 10, () => {
          console.log(this.starPoint[sct]);
          this.starArr[i].x = this.starPoint[sct].x;
          this.starArr[i].y = this.starPoint[sct].y;
          sct++;
          jellyStar(this.starArr[i], 0.5, () => {
            this.starArr[i].x = this.starPoint[sct1].x;
            this.starArr[i].y = this.starPoint[sct1].y;
            this.youyouItemYT(this.starArr[i],  randomNumber(20, 40), randomNumber(5, 8) / 5);
            sct1++;
          });
        });
      }
    }

    console.log('已重置星星---');
    if (null != this.imgArr && this.imgArr.length !== 0) {
      if (this.showPic_count >= this.imgArr.length) {
        this.showPic_count = 0;
      }
      console.log('选择用户上传图片');
      const obj = this.imgArr[this.showPic_count];
      this.showPic_count ++;
      if (obj.pic_url != null && obj.pic_url !== "") {
        this.mgPicShow.init(this.images.get(obj.pic_url));
      }
      if (obj.audio_url != null && obj.audio_url !== "") {
        this.playAudio(obj.audio_url);
      } else {
        this.playAudio('show_a');
      }
      const sx = this.picW / this.mgPicShow.width;
      const sy = this.picH / this.mgPicShow.height;
      const s = Math.min(sx, sy);
      this.mgPicShow.setScaleXY(s * 0.2);
      const cgxy = {
        x: this.canvasWidth / 2 + 2 * this.mapScale,
        y: this.canvasHeight / 2 - 135 * this.mapScaleY,
        scaleY: s * this.mapScale * 329 / 365,
        scaleX: s * this.mapScale,
        alpha: 1
      };
      tweenChange(this.mgPicShow, cgxy, 0.5, () => {
        jelly(this.mgPicShow, 0.5, () => {
          this.mic_url = obj.audio_url;
          this.move_Pic = false;
        });
      });
    } else {
      this.playAudio('show_a');
    }
    console.log('即将移动魔术手');
    // 移动魔术手
    moveItem(this.mgHand,  this.canvasWidth / 2 + 350 * this.mapScaleX ,
      this.canvasHeight / 2 + 40 * this.mapScale, 0.3, () => {
        this.youyouItem(this.mgHand);
      }, null, (item) => {
        console.log('移动魔术手');
        const st1 = new MySprite();
        st1.init(this.images.get('星星4'));
        st1.x = item.x - item.width / 4 + randomNumber(17, 22) * randomNumber(0, 3) * this.mapScale;
        st1.y = item.y - item.height / 4 - randomNumber(7, 12) * randomNumber(0, 3) * this.mapScale;
        this.renderArr.push(st1);
        tweenChange(st1, {alpha: 0}, 0.3);
      });
   const cgxydef = {
     x: this.canvasWidth / 2 + 4 * this.mapScale,
     y: this.canvasHeight / 2 - 135 * this.mapScaleY,
     scaleX: 1.3 * this.mapScale,
     scaleY: 1.3 * this.mapScale,
     alpha: 1
   };
    // 弹出图片背景框
    tweenChange(this.mgPicShow_def, cgxydef, 0.5, () => {
      jelly(this.mgPicShow_def, 0.5, () => {
        this.move_Pic = false;
      });
    });

   /**/
  }
  youyouItemY(item, y = 0) {
    if (!item) {
      return;
    }
    return moveItemYoyo(item, item.x,
      item.y + y * this.mapScale, 1, Infinity, true );
  }
  youyouItemYT(item, y = 20, time = 1) {
    if (!item) {
      return;
    }
    return moveItemYoyo(item, item.x,
      item.y + y * this.mapScale, time, Infinity, true );
  }
  // 悠悠
  youyouItem(item) {
    if (!item) {
      return;
    }
    return moveItemYoyo(item, item.x,
      item.y + 30 * this.mapScale, 1, Infinity, true );
  }

  homePStar() {
    // 小星星
    for (let i = 0; i < this.hpStarPoint.length; i++) {
      const star = new MySprite();
      star.init(this.images.get('星星' + randomNumber(2, 6)));
      star.x = this.hpStarPoint[i].x;
      star.y = this.hpStarPoint[i].y;
      star.alpha = 0;
      this.starHPArr.push(star);
      this.renderArr.push(star);
      // 设置显示
      if (i >= 0 && i < 2 ) {
        tweenChange(this.starHPArr[i], {alpha: 1}, 0.2, () => {
          tweenChange(this.starHPArr[i], {alpha: 0}, 0.2);
        });
      } else if (i >= 2 && i < 4 ) {
        tweenChange(this.starHPArr[i], {alpha: 1}, 0.6, () => {
          tweenChange(this.starHPArr[i], {alpha: 0}, 0.2);
        });
      } else if (i >= 4 && i < 6 ) {
        tweenChange(this.starHPArr[i], {alpha: 1}, 0.3, () => {
          tweenChange(this.starHPArr[i], {alpha: 0}, 0.4);
        });
      } else if (i >= 6 && i < 8 ) {
        tweenChange(this.starHPArr[i], {alpha: 1}, 0.6, () => {
          tweenChange(this.starHPArr[i], {alpha: 0}, 0.3);
        });
      } else if (i >= 8 && i < 10 ) {
        tweenChange(this.starHPArr[i], {alpha: 1}, 0.4, () => {
          tweenChange(this.starHPArr[i], {alpha: 0}, 0.3);
        });
      } else if (i >= 10 && i < 12 ) {
        tweenChange(this.starHPArr[i], {alpha: 1}, 0.7, () => {
          tweenChange(this.starHPArr[i], {alpha: 0}, 0.3);
        });
      } else if (i >= 12 && i < 14 ) {
        tweenChange(this.starHPArr[i], {alpha: 1}, 0.1, () => {
          tweenChange(this.starHPArr[i], {alpha: 0}, 0.3);
        });
      } else if (i >= 14 && i < 16 ) {
        tweenChange(this.starHPArr[i], {alpha: 1}, 0.5, () => {
          tweenChange(this.starHPArr[i], {alpha: 0}, 0.3);
        });
      } else if (i >= 16 && i < 18 ) {
        tweenChange(this.starHPArr[i], {alpha: 1}, 0.2, () => {
          tweenChange(this.starHPArr[i], {alpha: 0}, 0.3);
        });
      } else {
        tweenChange(this.starHPArr[i], {alpha: 1}, 0.7, () => {
          tweenChange(this.starHPArr[i], {alpha: 0}, 0.3);
        });
      }
    }
  }

  // 显示和隐藏星星
  showOrAlpStar(alp) {
    this.starArr = [];
    // 小星星
    for (let i = 0; i < this.starPoint.length; i++) {
      if (this.starArr.length < 8) {
        const star = new MySprite();
        star.init(this.images.get('星星' + randomNumber(2, 6)));
        console.log('小星星' + randomNumber(2, 6));
        star.alpha = 0;
        star.x = this.starPoint[i].x;
        star.y = this.starPoint[i].y;
        /*      this.starPoint.push(this.starPoint[i]);*/
        this.starArr.push(star);
        this.renderArr.push(star);
      }

      // 设置显示
      tweenChange(this.starArr[i], {alpha: alp},  randomNumber(7, 11) / 10, () => {

        jellyStar(this.starArr[i], 0.5, () => {
          // this.youyouItem(this.starArr[i]);
          this.youyouItemYT(this.starArr[i],  randomNumber(20, 40), randomNumber(5, 8) / 5);
        });
      });
    }
  }


  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);


  }



}
