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

import {
  Label,
  MySprite, tweenChange, MyAnimation, randomSortByArr, ShapeRect, getMinScale, showPopParticle, moveItem, removeItemFromArr, rotateItem, showStar, showItem, alphaItem, endShow, hideItem,

} 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 = 'ssy003';


 
  picIndex = 0;
  cardArr = [];
  picArr


  canTouch = false;

  curPic;

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

  ngOnInit() {


    const getData = (<any> window).courseware.getData;
    getData((data) => {

      if (data && typeof data == 'object') {
        this.data = data;
      } else {
        this.data = {};
      }

      console.log('data:' , data);
      if (!this.data.contentObj) {
        this.data.contentObj = {};
      }


      this.initListener();
      this.initDefaultData();



      console.log("canvasdefout+"+this.canvas);
      this.initAudio();
      this.initImg();
      

    }, 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.randomItemCard();
    this.initView(); 
    console.log("qqqqqqqqqqqqqqqqqq");
  }


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



  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() {


    //将图片一一传到卡片上
    const picArr = this.data.contentObj.picArr; 
    if (!picArr || picArr.length == 0) {

      const picArr = [];
      picArr.push({
        
        pic_url:'', audio_url: "assets/play/music/card.mp3", title: "1" 
      });
      picArr.push({
        
        pic_url:'', audio_url: "assets/play/music/card.mp3", title: "2" 
      });
      picArr.push({
        
        pic_url:'', audio_url: "assets/play/music/card.mp3", title: "3" 
      });
      picArr.push({
        
        pic_url:'', audio_url:"assets/play/music/card.mp3", title: "4" 
      });

   
      this.data.contentObj.picArr = picArr;

    }



}


initAudio() {

  const contentObj = this.data.contentObj;
  if (!contentObj) { return; }

  const addUrlToAudioObj = (audioUrl) => {

    if (audioUrl) {
      
      // console.log('audioUrl:', audioUrl);
      const audio = new Audio();
      audio.src = audioUrl;
      audio.load();
      this.audioObj[audioUrl] = audio;
    }
  };


  const arr = contentObj.picArr;

  if (arr) {
    for (let i = 0; i < arr.length; i++) {
      addUrlToAudioObj(arr[i].audio_url);

    }
  }




  const audioObj = this.audioObj;
  const addOneAudio = (key, url, vlomue = 1, loop = false, callback = null) => {

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

    audioObj[key] = audio;

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


 // addOneAudio('sm-back', this.rawAudios.get('sm-back'), 1);
 // addOneAudio('sm-display', this.rawAudios.get('sm-display'), 1);
  //addOneAudio('sm-wrong', this.rawAudios.get('sm-wrong'), 1);
 // addOneAudio('sm-win', this.rawAudios.get('sm-win'), 1); 
 // addOneAudio('sm-in', this.rawAudios.get('sm-in'), 1); 
  addOneAudio('touzi', this.rawAudios.get('touzi'), 1); 
  addOneAudio('card', this.rawAudios.get('card'), 1); 
  addOneAudio('start', this.rawAudios.get('start'), 1); 

  // this.successAudio.onended = () => {
  //   // this.showSuccessAudio();
  // };


}

initImg() {

  const contentObj = this.data.contentObj;
  if (contentObj) {


    const addPicUrl = (url) => {
      if (url) {
          this.rawImages.set(url, url);
        }
    };


    const arr = this.data.contentObj.picArr;
    if (arr) {
    
      for (let i = 0; i < arr.length; i++) {
        addPicUrl( arr[i].pic_url);
  
    
      }
    }

  }


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

}





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

    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;



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

    // this.mapScale = this.canvasWidth / this.canvasBaseW;
    // this.mapScale = this.canvasHeight / this.canvasBaseH;
    this.renderArr = [];
 
 
    


    if (!this.data.contentObj.picArr) {
      this.data.contentObj.picArr = [];
    }
    this.picArr = this.data.contentObj.picArr;

    this.cardArr = [];


  }



  /**
   * 初始化试图
   */
  initView() { 
    //加背景
    this.initBg();
    //加流星
    this.Animation();
    //加开始按钮
    this.startBtn();
    //骰子在屏幕一直呼吸
    //声明骰子
    this.stouzi();
    //骰子呼吸动画

}
a
big(){

    const tween=tweenChange(this.tz, {scaleX: 1.1, scaleY: 1.1}, 1 , ()=>{  
       this.small(); 
    });
    this.a=tween;
    
  
  

}
w
small(){
 
    const tween=tweenChange(this.tz, {scaleX: 1, scaleY: 1}, 1 , ()=>{      
     
        this.big(); 
    
    });
    this.w=tween;
    


}


stouzi(){
   //声明骰子
   this.tz=new MySprite();
  
   this.t= new MySprite(); 
   this.tz.addChild(this.t);
  
   
   this.t.init(this.images.get("t1"));
   this.startBorder.addChild(this.tz);
   this.tz.setScaleXY(this.mapScale/1.2);
   this.tz.y=-50;
  
}

Btn
stn
retn
startBtn(){

 
    const allwidth=((this.cardArr.length/2)*280+(this.cardArr.length/2-1)*56)*this.mapScale;

    this.Btn= new MySprite();
    this.stn= new MySprite();
    this.retn= new MySprite();

    this.stn.init(this.images.get("stn"));
    this.retn.init(this.images.get("retn"));

    this.Btn.addChild(this.stn);
    this.Btn.addChild(this.retn);
    this.startBorder.addChild(this.Btn);
    this.stn.visible=true;
    this.retn.visible=false;
    this.Btn.setScaleXY(this.mapScale/1.5);
    this.b=0;
    this.Btn.y=200;



  

  
}
s1
Animation(){
  this.endPageArr = [];
  this.endPageArr.push(this.s1);
  this.showPetalFlag = true;
  this.s1=new MySprite();
  this.s1.init(this.images.get("star"));
  this.s1.x=this.canvasWidth;
  this.s1.y=-1.2*this.canvasHeight;

  this.startBorder.addChild(this.s1);
  
  const randomT = 9;
  this.s1['time'] = randomT;
  moveItem(this.s1, -(this.canvasWidth + this.s1.width * this.s1.scaleX), this.canvasHeight + this.s1.height * this.s1.scaleY, this.s1['time'], () => {
    removeItemFromArr(this.endPageArr, this.s1);
  });
  setTimeout(() => {
    this.Animation();
  },2000);
 




}
addPetal() {

  if (!this.showPetalFlag) {
    return;
  }

  const petal = this.getPetal();
  this.endPageArr.push(petal);

  moveItem(petal, petal.x, this.canvasHeight + petal.height * petal.scaleY, petal['time'], () => {
    removeItemFromArr(this.endPageArr, petal);
  });

  rotateItem(petal, petal['tr'], petal['time']);

  setTimeout(() => {
    this.addPetal();
  }, 100);

}
getPetal() {

  const petal = new MySprite(this.ctx);

  const id = Math.ceil( Math.random() * 4 );
  petal.init(this.images.get('petal_' + id));

  const randomS = (Math.random() * 0.4 + 0.6) * this.mapScale;
  petal.setScaleXY(randomS);

  const randomR = Math.random() * 360;
  petal.rotation = randomR;

  const randomX = Math.random() * this.canvasWidth;
  petal.x = randomX;
  petal.y = -petal.height / 2 * petal.scaleY;

  const randomT = 2 + Math.random() * 5;
  petal['time'] = randomT;

  let randomTR = 360 * Math.random(); // - 180;
  if (Math.random() < 0.5) { randomTR *= -1; }
  petal['tr'] = randomTR;

  return petal;
}

bg
startBorder
initBg() { 

  const bg = new ShapeRect();
    bg.fillColor = '#75d100';
    bg.setSize(this.canvasWidth, this.canvasHeight);
    this.renderArr.push(bg); 
    this.bg = bg;

 
  //把图片填充入背景，全覆盖
  this.startBorder = new MySprite();
  this.startBorder.init(this.images.get('BG'));
  this.startBorder.x = this.canvasWidth / 2 ;
  this.startBorder.y = this.canvasHeight / 2 ;
  const sx = this.canvasWidth / this.startBorder.width;
  const sy = this.canvasHeight / this.startBorder.height;
  const s=Math.max(sx,sy);
  console.log(s+"s");
  this.startBorder.setScaleXY(s);
  this.renderArr.push(this.startBorder); 



  
}
count=0;
active=1;
  mapDown(event) { 

    //点击按钮，骰子竖直跳下来，卡片弹出来
    if (this.checkClickTarget(this.stn)&&(this.b==0)) {
      this.canTouch=false;
    
       
      this.big();
      this.startGame(); 
      return;
    }
    if (this.checkClickTarget(this.retn)&&(this.b==1)) {

      console.log("bbbbb"+this.b);
      this.canTouch = false; 
     
      for(let i=0;i<this.cardArr.length;i++){
        tweenChange(this.cardArr[i], {scaleX: 0, scaleY: 0}, 0.3, ()=>{
        });
      }
     
      this.tz.visible=true;
      this.tz.setScaleXY(this.mapScale/1.5);
      this.tz.y=-50;
      
     // this.big();

      
     
      
      this.startGame(); 

   }

    //点击骰子，随机选卡]
   
    if (this.checkClickTarget( this.t)) {

      console.log(this.canTouch+"-----00000000000");
      this.a.stop();
      this.w.stop();
      this.canTouch = false; 
      console.log(this.canTouch+"-----0000000000011111111");
      this.starttouzi();
     
      
      return;
    }
    
       //点击图片正面的动作 
       for(let i=0;i<this.cardArr.length;i++){
        let card = this.cardArr[i];
        let cardBg = card.children[1];
        
        console.log("i"+i);
       
      
        if (this.checkClickTarget(cardBg)&&(this.bs[i]==1)){ 
          console.log("contc"+this.countc);
          this.countc++;
          let lcard;
          lcard=this.cardArr[this.x];
          if(this.countc==1){ 
           
          }
          else{
            const audio = this.audioObj[lcard["audio_url"]];
            audio.pause();
            audio.currentTime = 0;
  
  
          }
       
          
          
  
          
    
          this.playAudio(card["audio_url"]); 
      
          this.x=i;
  
          console.log("i-"+i);
          this.playAudio(card["audio_url"]); 
      
          
                  
  
          return;
        }
       
      
      }
       
   

  }
  countc=0;
  x
  starttouzi(){
    
    this.count++;
    
   
    //骰子转动，给一个随机数
    this.canTouch = false; 
    this.tAnimation();
    if(this.count==6){
      this.count=0;
      setTimeout(() => {
         //骰子消失
       console.log("消失骰子数"+this.t);

      
    //  hideItem(this.tz);
      this.tz.visible=false;
      
      //重新开始按钮 
      this.stn.visible=false;
      this.retn.visible=true;
      this.b=1;
      setTimeout(() => {
        tweenChange(this.Btn, {scaleX: 1, scaleY: 1}, 0.3 , ()=>{      
        });    
      }, 180); 
           
      }, 4000); 
     
    }
    

  }
  b
  btnIn1(item){
    this.playAudio("sm-in");
    tweenChange(item, {y: 200}, .3);
  }
  btnOut(item){
    this.playAudio("sm-out");
    let out = this.canvasWidth+200*this.mapScale;
    tweenChange(item, {y: out}, 3);
  }
//开始游戏
  startGame(){
    this.canTouch = false; 
    this.playAudio("start");
    //生成随机数组
    
    
    if(this.count==0){
      this.randomtz();
    }
    //按钮消失
    tweenChange(this.Btn, {scaleX: 1.2, scaleY: 1.2}, 0.3 , ()=>{      
    });
    setTimeout(() => {
      tweenChange(this.Btn, {scaleX: 0, scaleY: 0}, 0.3 , ()=>{      
      });    
    }, 180);  
    //卡片弹出来
    setTimeout(() => {
      this.initCard();  
    }, 180);  
     //骰子掉下来
    setTimeout(() => {
      this.touzi();
    }, 300);  
  }
  
  tz
  t;
  randomt
  touzi(){
   
    //骰子掉下来
    this.btnIn1(this.tz);
  
  }
 
  fancard(){
    
    this.overCard(this.cardArr[this.randomt],()=>{
    });

  }
  tAnimation(){
    
      this.randomt = this.newball[0];
      this.playAudio("touzi");
      this.canTouch = false; 
      console.log("this.a"+this.a);
     
      
      
     
     
      console.log(this.t[this.randomt]+"kongmei22222222");
      const animation=new MyAnimation();
      for(let j=0;j<6;j++){
      for(let i=0;i<6;i++){
        const imgobj=this.images.get('touzi'+i);
        animation. addFrameByImg(imgobj);

      }
    }

      animation.delayPerUnit=0.08;
      //骰子旋转
      animation.play();
      
      animation.playEnd=() => {
        if(this.data.sideA==1)
        {
          //默认正面
          this.bs[this.randomt]=0;
        }
        if(this.data.sideB==1){
          this.bs[ this.randomt]=1;
        }
        animation.stop(); 
        console.log("---------"+this.randomt);
        let x=3;
      //  this.t.init(this.images.get("t"+x));
        this.t.init(this.images.get("t"+(this.randomt+1)));
        this.overCard(this.cardArr[this.randomt],()=>{
          this.showParticle(this.cardArr[this.randomt]);     
        });
        console.log("old"+this.newball);
        this.newball.splice(0,1);
        console.log("new+"+this.newball);
        this.a.start();
        this.w.start();
    
      };   
      
     
      this.tz.addChild(animation);
    
  }
  ss1
  ss2
  ss3
  ss4
  showParticle(card){ 
    this.ss1=new MySprite();
    this.ss1.init(this.images.get("ss"));
    card.addChild(this.ss1);
    this.ss1.x=-100;
    this.ss1.y=100;
    showItem(this.ss1);

    this.ss2=new MySprite();
    this.ss2.init(this.images.get("ss"));
    card.addChild(this.ss2);
    this.ss2.x=-120;
    this.ss2.y=80;
    showItem(this.ss2);

    this.ss3=new MySprite();
    this.ss3.init(this.images.get("ss"));
    card.addChild(this.ss3);
    this.ss3.x=130;
    this.ss3.y=-60;
    showItem(this.ss3);

    this.ss4=new MySprite();
    this.ss4.init(this.images.get("ss"));
    card.addChild(this.ss4);
    this.ss4.x=120;
    this.ss4.y=-90;
    this.ss4.setScaleXY(2*this.mapScale);
    showItem(this.ss4);

    hideItem(this.ss1);
    hideItem(this.ss2);
    hideItem(this.ss3);
    hideItem(this.ss4);

   // showStar(this.ss,0.4);
   // showPopParticle(this.images.get('ss'), {x: card.x/6.8,y: card.y-400} ,this.startBorder);
  }

oldball
newball
  randomtz(){
    this.oldball=[0,1,2,3,4,5];
    this.oldball=randomSortByArr(this.oldball);
    this.newball=this.oldball;
  }
  endPageArr;
  showPetalFlag;
  
  initCard(){
    this.randomItemCard();
 //   this.cardArr = randomSortByArr(this.cardArr); //重新排序卡片组 
    this.initItemCard();//设定卡片的位置

    //卡片恢复之前的状态
    for(let i=0;i<this.cardArr.length;i++){
      let card = this.cardArr[i];
      card.setScaleXY(this.mapScale);
      card.alpha = 1;
    }
    this.StartAnimation(this.cardArr);
  }
  initItemCard(){
    
    const picLength = this.cardArr.length;
    
    const top = (120)*this.mapScale;//第一排
    const top2 = (212+160)*this.mapScale;//第二排

    const allWidth = ((picLength/2)*280+(picLength/2-1)*80)*this.mapScale;

    const drawItem = (index)=>{ 
      //设置卡片间距
      let itemBack = this.cardArr[index];  
      itemBack.x = (this.canvasWidth-allWidth)/2+((Math.floor(index/2)*(253+55))+200)*this.mapScale;
      if(index%2==0){ 
        itemBack.y = top;  
      }else{
        itemBack.y = top2;  
      }
      itemBack.setScaleXY(this.mapScale);
      this.renderArr.push(itemBack); 
 
    };
    const drawItem2 = (index)=>{ 
      let itemBack = this.cardArr[index];  
      //itemBack.x = ((this.canvasWidth-allWidth)/2)*this.mapScale;
      if(index%2==0){ 
        itemBack.x = top*2+100;  
      }else{
        itemBack.x = top2*2-170;  
      }
      itemBack.y = top*2-30;  
      
      itemBack.setScaleXY(this.mapScale);
      this.renderArr.push(itemBack); 
 
    };
    if(picLength==2){
      for(let i=0;i<picLength;i++){
        drawItem2(i); 
      }  
    }else{
      for(let i=0;i<picLength;i++){
        drawItem(i); 
      }

    }
        

  }

  StartAnimation(cardArr){ 
    //卡片渐进显示
    /*for(let i=0;i<cardArr.length;i++){
      tweenChange(cardArr[i], {alpha: 1}, 0.3, ()=>{
        setTimeout(() => {
          this.playAudio("sm-back");
          this.overCard(cardArr[i],()=>{
            this.canTouch = true;
          });
          
        }, 1000);
      });
    }*/
  
    for(let i=0;i<cardArr.length;i++){
      tweenChange(cardArr[i], {scaleX: 0, scaleY: 0}, 0, ()=>{
        
      });
      setTimeout(() => {
        tweenChange(cardArr[i], {scaleX: 1, scaleY: 1}, 0.3);
       
     
      }, 1000);
    }
  }
  
  overCard(item , callback?: any){ 
    let w = item.scaleX;
    this.playAudio("card");
    tweenChange(item, {scaleX: 0}, 0.3,()=>{
      item.children[2].visible = !item.children[2].visible;
      tweenChange(item, {scaleX: w}, 0.3,()=>{
        callback&&callback();
      });
    });
  }
  
  front
back=[]
bs=[];
  randomItemCard(){ 
    
    this.cardArr = [];
    for(let i=0;i<6;i++){
      let item = this.picArr[i];
      let pic = new MySprite();
      //初始化设置为隐藏
      pic.alpha = 1;
      pic.childDepandAlpha = true;
      //声明正反面的对象
      this.back[i] = new MySprite(); 
      this.front = new MySprite();
      this.front.init(this.images.get("front"));
     
      //设置索引
      pic["index"] = i;   
      //给正反面添加默认的显示图片
     // this.back1.init(this.images.get("cardBg6"));   
     // this.front1.init(this.images.get("frontBg"));
      //内嵌框
      let bgRect = new ShapeRect();
      bgRect.setSize(180, 180);
      bgRect.init();
      bgRect.fillColor = '#ff83fa';
      this.front.addChild(bgRect, -1);
      
      

      //把设置好的正反面变量放到卡片组里

      if(this.data.sideA==1){

  
        //如果选择默认是正面,bs=0
        for(let i=0;i<this.picArr.length;i++){
          this.bs[i]=1;
        }

        
        pic.addChild(this.back[i]);
        pic.addChild(this.front);
       
      }
      else if(this.data.sideB==1){
        for(let i=0;i<this.picArr.length;i++){
          this.bs[i]=0;
        }

        pic.addChild(this.front);

        pic.addChild(this.back[i]);
         
      }

      //音频路径做属性保存，方便点击卡片播放
      if(item.audio_url){
        pic["audio_url"] = item.audio_url;
        console.log(item.audio_url+"pic-audio");  

      }
      const maxLen = 160;
      if(item.pic_url){
        let pic = new MySprite();
        pic.init(this.images.get(item.pic_url));  

       //如果是横图设置图片填充卡片正面的比例     
        if(pic.width>=pic.height){
          pic.setScaleXY(getMinScale(pic,  maxLen-15));
          pic.x=2;
          this.front.addChild(pic);
        } 
      
        //如果是竖图设置图片填充卡片正面的比例
        if(pic.width<pic.height&&(pic.width+40)>=pic.height){
          pic.setScaleXY(getMinScale(pic,  maxLen));
          pic.x=0;
          pic.y=-3;

        }
        //如果是正方图设置图片填充卡片正面的比例
        if(pic.width<pic.height&&(pic.width+40)<pic.height){
          pic.setScaleXY(getMinScale(pic,  maxLen-10));
          pic.x=-5;
          pic.y=-6;

        }      
        this.front.addChild(pic);
      }else{
        const label = new Label();
        label.text = item.title;
        label.fontName = 'BRLNSDB';
        label.fontColor = '#ed3a33';
        label.fontSize = 200;
        label.textAlign = 'center';
        
        label.setMaxSize((bgRect.width - 20)+10);
        console.log(bgRect.width - 20+"卡片文字位置");
        this.front.addChild(label);
      }     
      this.cardArr.push(pic); 
      this.cardArr[i].alpha=1;
   
    } 
    this.back[0].init(this.images.get("back0"));
    this.back[4].init(this.images.get("back0"));
    this.back[1].init(this.images.get("back1"));
    this.back[5].init(this.images.get("back1"));
    this.back[3].init(this.images.get("back2"));
    this.back[2].init(this.images.get("back2"));
 
  }

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


  }



}
