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

import {
  MySprite,
  RichText,
  getMinScale,
  ShapeRect,
  ShapeCircle,
  tweenChange,
  randomSortByArr,
  Label,
  showPopParticle,
  moveItem,
  removeItemFromArr,
  rotateItem,
  hideItem,
  showItem,
  ShapeRectNew,
  scaleItem,
  showBlingBling,
  waterWave,
  jelly,
  getAngleByPos,
  getPosDistance,
  shake
} from "./Unit";

import { localImages, localAudios } from "./resources";

import { Cartoon } from './Cartoon'
import { Subject } from "rxjs";
import { debounceTime, map, takeWhile, retry } from "rxjs/operators";
import * as _ from "lodash";
import TWEEN from "@tweenjs/tween.js";

const defauleFormData = require('../../assets/default/formData/LST01/demo.json')


const zIndexMap = {
  mainBackground: 0,
  answerCard: 100,
  questionCard: 100,
  questionKuang: 50,
  imageContainer: 20,
  shortAudio: 60,
  progressBar: 55,
  animation:200
}

@Component({
  selector: "app-play",
  templateUrl: "./play.component.html",
  styleUrls: ["./play.component.scss"]
})

export class PlayComponent implements OnInit, OnDestroy {
  
  g_cartoon = new Cartoon()

  // ------------  全局数据  ------------
  g_stage; //中心舞台
  // g_background_color = "#rgb(0,0,0,0)"
  g_background_color = "#af7cb7"
  g_enableMapDown = true; // 触摸使能
  g_enableMapUp = true; // 抬起使能
  g_enableMapMove = true; // 移动ss使能
  g_canvasLeft;
  g_canvasTop;
  g_animationId: any;
  g_mapScale = 1; // 缩放比例
  g_KEY = "DataKey_LST01";
  g_canvasWidth = 1280;
  g_canvasHeight = 720;
  g_canvasBaseW = 1280;
  g_canvasBaseH = 720;
  g_winResizeEventStream = new Subject();
  g_clickX; // 点击坐标 X
  g_clickY; // 点击坐标 Y
  g_ctx; // canvas 实例
  g_data; // 数据
  g_formData; // 核心表单数据
  g_teacherFlag = false; // 默认角色
  g_currentUser;
  g_firstTouch = true;
  g_partTitle_x = null;
  g_mainTitle_x = null;
  g_maskLayerZindex = 999;
  // ------------------------------------

  // ------------  私有数据  ------------
  m_mapDownQueue = {} //按下事件处理队列
  m_mapDownArray = [] //按下事件处理队列
  m_mapDownObject = []

  m_mapUpQueue = {} //抬起事件处理队列
  m_mapUpArray = [] //抬起事件处理队列
  m_mapUpObject = []

  m_mapMoveArray = [] //移动事件处理队列
  m_mapMoveObject = []
  m_endPageArr;
  m_showPetalFlag;
  m_elementPetalArr;
  m_showElementPetalFlag;
  m_PetalImage = "_scrap-pic-"  // 飘落动画
  m_renderArr // 渲染队列
  m_renderObject = [];
  m_defaultZindex = 0;
  m_setTimeoutIDs = [];
  m_setIntervalIDs = [];
  m_moveAsstantIntervalId = null;
  // ------------------------------------
  

  // ------------  游戏逻辑数据  ------------
  m_highLight_All = []
  m_answerCard_All = []
  m_questionCard_All = []
  m_enableCardMove = false;
  m_currentSelectedCardID = null;
  m_startGame = true
  // ------------------------------------


  // ------------  消息  ------------
  
  // ------------------------------------


  // ------------  调试变量  ------------
  g_EnableStageRuler = false; // 使能舞台背景格尺
  g_ForceChangeDefaultRole = false // 强制当前角色为默认角色
  g_EnableTestSendEvent = false // 发送模拟Web数据
  g_EnableLeftCornerTest= false // 测试左上角图标
  // ------------------------------------


  // 当数据加载完毕后，执行
  systemReady(){
    if(this.g_EnableLeftCornerTest){
      this.setLeftCornerTest()
    }
    this.initGame()
  }
  
  // 屏幕尺寸变化后执行
  handleScreenResize(){
    this.initSystem();
    this.cleanSystemVar()
    this.cleanGameVar();
    if(this.g_EnableLeftCornerTest){
      this.setLeftCornerTest()
    }
    this.initGame()
  }

  // 映射预加载图片[网路]资源 返回包含图片路径的数组
  mapToImageArray(contentObj){
    let array = []
    this.g_formData.dataArray.forEach(element => {
      if(element.image_url){
        array.push(element.image_url)
      }
    });
    if(this.g_formData.question.image_url){
      array.push(this.g_formData.question.image_url)
    }
    return array
  }

  // 映射预加载音频[网路]资源 返回包含音频路径的数组
  mapToAduioArray(contentObj){
    let array = []
    if(this.g_formData.question.longAudio_url){
      array.push(this.g_formData.question.longAudio_url)
    }
    if(this.g_formData.question.shortAudio_url){
      array.push(this.g_formData.question.shortAudio_url)
    }
    return array
  }

  // ------------------------------------------------------------------------------
  // 游戏核心处理区
  // ------------------------------------------------------------------------------
  // ------------------------------------------------------------------------------
  // 
  // 
  // 
  // ------------------------------------------------------------------------------
  // ------------------------------------------------------------------------------

  initGame(){
    console.log(this.g_formData);
    this.initBackground();
    this.initCardsAll();
    this.initQuestion();
    this.initCat();
    this.initWellDone();
  }

  cleanGameVar(){
    let audioProgress = this.g_cartoon.getCartoonElement("audio-plyer-progress")
    if(audioProgress && audioProgress.audio){
      audioProgress.audio.pause()
      audioProgress.audio.currentTime = 0;
      let slider = this.g_cartoon.getCartoonElement("audio-plyer-slider")
      if(slider.enableSlider){
        slider.release()
        this.disableMoveAsstant();
      }
    }
    this.m_currentSelectedCardID = null;
    this.m_enableCardMove = false;
    this.m_answerCard_All = [];
    this.m_questionCard_All = [];
    this.m_startGame = true;
    this.m_highLight_All = []
  }

  startGame(){

  }

  restartGame(){
    this.cleanGameVar()
    this.startGame()
  }

  endGame(){
    let audioPlayer = this.g_cartoon.getCartoonElement("bg-short-audio")
    if(audioPlayer && audioPlayer.isPlaying){
      audioPlayer.playIcon.ref.visible = true
      audioPlayer.pauseIcon.ref.visible = false
      audioPlayer.audio.pause()
      audioPlayer.isPlaying = !audioPlayer.isPlaying
    }
    this.g_cartoon.playAudio("xingxing")
    this.showBlingStar(this.g_cartoon.getCartoonElement("background-main-desk").ref, ()=>{
      this.showEndPatal();
      this.g_cartoon.playAudio("sahua")
      this.showMaskLayer(0.3)
      this.g_cartoon.getCartoonElement("well-done").popup()
      this.g_cartoon.playAudio("sm-choice-complete", false, ()=>{
        this.stopEndPatal();
      })
      this.m_startGame = false;
    })

    
  }

  initCat() {
    let element = this.g_cartoon.createCartoonElementImageFunc("background-main-cat", "bg_cat", (w, h)=>{
      let sx = (185 * this.g_mapScale) / w
      let sy = (125 * this.g_mapScale) / h
      return {
        sx: sx,
        sy: sy
      }
    }, (w, h)=>{
      return {
        x: this.g_cartoon.getOrigin().x + (103 + 185 / 2) * this.g_mapScale,
        y: this.g_cartoon.getOrigin().y + (210 + 125 / 2) * this.g_mapScale
      }
    })

    element.ref.y = this.g_cartoon.getOrigin().y + (320 + 125 / 2) * this.g_mapScale

    if(this.g_formData.dataArray.length) {
      element.setp = 110 / this.g_formData.dataArray.length
    } else {
      element.setp = 110
    }

    element.stepUp = (callback?)=>{
      let nextY = element.ref.y - element.setp * this.g_mapScale
      tweenChange(element.ref, {y: nextY}, 0.5, ()=>{
        callback && callback()
      })
    }

    this.render(element.ref, 3)
  }
  
  initBackground(){
    let element = this.g_cartoon.createCartoonElementImageFunc("background-main-desk", "bg_desk", (w, h)=>{
      let sx = (1374 * this.g_mapScale) / w
      let sy = (466 * this.g_mapScale) / h
      return {
        sx: sx,
        sy: sy
      }
    }, (w, h)=>{
      return {
        x: this.g_canvasWidth / 2,
        y: this.g_cartoon.getOrigin().y + (300 + 466 / 2) * this.g_mapScale
      }
    })
    this.render(element.ref, 5)

    element = this.g_cartoon.createCartoonElementImageFunc("background-main-wall", "bg_wall", (w, h)=>{
      let sx = this.g_canvasWidth / w
      let sy = this.g_canvasHeight / h

      return {
        sx: sx,
        sy: sy
      }
    }, (w, h)=>{
      return {
        x: this.g_canvasWidth / 2,
        y: this.g_canvasHeight / 2
      }
    })
    this.render(element.ref, 1)

    element = this.g_cartoon.createCartoonElementImageFunc("background-question-image-text", "bg_tigan", (w, h)=>{
      return {
        sx: 690 * this.g_mapScale / w,
        sy: 375 * this.g_mapScale / h
      }
    }, (w, h)=>{
      return {
        x: this.g_cartoon.getOrigin().x + (294 + 690 / 2) * this.g_cartoon.mapScale,
        y: this.g_cartoon.getOrigin().y + (9 + 375 / 2) * this.g_cartoon.mapScale,
      }
    })
    this.render(element.ref, 10)

    element = this.g_cartoon.createCartoonElementImageFunc("background-question-audio", "bg_yinpin", (w, h)=>{
      return {
        sx: 505 * this.g_mapScale / w,
        sy: 375 * this.g_mapScale / h
      }
    }, (w, h)=>{
      return {
        x: this.g_cartoon.getOrigin().x + (386 + 505 / 2) * this.g_cartoon.mapScale,
        y: this.g_cartoon.getOrigin().y + (9 + 375 / 2) * this.g_cartoon.mapScale,
      }
    })

    let staticLongAudioIcon = this.g_cartoon.createCartoonElementImageFunc("background-question-long-audio-static-icon", "btn_yin", (w, h)=>{
      return {
        sx: 254 / w,
        sy: 212 / h
      }
    }, (w, h)=>{
      return {
        x: 0,
        y: 0
      }
    })
    element.ref.addChild(staticLongAudioIcon.ref)

    let longAudioAniContainer = this.g_cartoon.createCartoonElementImageFunc("background-question-long-audio-ani-icon", "btn_yin_ani", (w, h)=>{
      return {
        sx: 254 / w,
        sy: 212 / h
      }
    }, (w, h)=>{
      return {
        x: 0,
        y: 0
      }
    })
    element.ref.addChild(longAudioAniContainer.ref)
    longAudioAniContainer.ref.visible = false;

    staticLongAudioIcon.audioUrl = null;
    if(this.g_formData.question.longAudio_url) {
      staticLongAudioIcon.audioUrl = this.g_formData.question.longAudio_url
    }

    this.subscribeMapDownEvent(staticLongAudioIcon.id, ()=>{
      staticLongAudioIcon.ref.visible = false;
      longAudioAniContainer.ref.visible = true;
      if(staticLongAudioIcon.audioUrl) {
        longAudioAniContainer.playAni = this.g_cartoon.createAnimation("btn_yin", 4, 500)
        longAudioAniContainer.playAni.loop = true;
        longAudioAniContainer.ref.addChild(longAudioAniContainer.playAni)
        longAudioAniContainer.playAni.play()
        this.g_cartoon.playAudio(staticLongAudioIcon.audioUrl, false, ()=>{
          staticLongAudioIcon.ref.visible = true;
          longAudioAniContainer.ref.visible = false;
          this.deleteElementInRender(longAudioAniContainer.playAni.id)
        })
      }
      this.g_enableMapDown = true;
    })

    this.render(element.ref, 15)

    let staticShortAudioIcon = this.g_cartoon.createCartoonElementImageFunc("background-question-short-audio-static-icon", "btn_laba", (w, h)=>{
      return {
        sx: 187 * this.g_mapScale / w,
        sy: 209 * this.g_mapScale / h
      }
    }, (w, h)=>{
      return {
        x: this.g_cartoon.getOrigin().x + 996 * this.g_mapScale + (187/2) * this.g_mapScale,
        y: this.g_cartoon.getOrigin().y + 178 * this.g_mapScale + (209/2) * this.g_mapScale,
      }
    })
    this.render(staticShortAudioIcon.ref, 10)

    let shortAudioAniContainer = this.g_cartoon.createCartoonElementImageFunc("background-question-short-audio-ani-icon", "btn_laba_ani", (w, h)=>{
      return {
        sx: 187 * this.g_mapScale / w,
        sy: 209 * this.g_mapScale / h
      }
    }, (w, h)=>{
      return {
        x: this.g_cartoon.getOrigin().x + 996 * this.g_mapScale + (187/2) * this.g_mapScale,
        y: this.g_cartoon.getOrigin().y + 178 * this.g_mapScale + (209/2) * this.g_mapScale,
      }
    })
    this.render(shortAudioAniContainer.ref, 10)
    shortAudioAniContainer.ref.visible = false;

    staticShortAudioIcon.audioUrl = null;
    if( this.g_formData.question.type != "LongAudio" && this.g_formData.question.shortAudio_url) {
      staticShortAudioIcon.audioUrl = this.g_formData.question.shortAudio_url

      this.subscribeMapDownEvent(staticShortAudioIcon.id, ()=>{
        staticShortAudioIcon.ref.visible = false;
        shortAudioAniContainer.ref.visible = true;
        if(staticShortAudioIcon.audioUrl) {
          shortAudioAniContainer.playAni = this.g_cartoon.createAnimation("btn_laba", 4, 500)
          shortAudioAniContainer.playAni.loop = true;
          shortAudioAniContainer.ref.addChild(shortAudioAniContainer.playAni)
          shortAudioAniContainer.playAni.play()
          this.g_cartoon.playAudio(staticShortAudioIcon.audioUrl, false, ()=>{
            staticShortAudioIcon.ref.visible = true;
            shortAudioAniContainer.ref.visible = false;
            this.deleteElementInRender(shortAudioAniContainer.playAni.id)
          })
        }
        this.g_enableMapDown = true;
      })

      this.render(element.ref, 15)
    } else {
      staticShortAudioIcon.ref.visible = false;
      shortAudioAniContainer.ref.visible = false;
    }
  }

  initCardsAll(){
    this.initAnsterCard_Image();
    this.initQuestionCard_Image()
  }

  // 问题卡片 图片
  initQuestionCard_Image(){
    this.g_formData.dataArray.forEach((item, index)=>{
      this.m_questionCard_All.push(this.createQuestionCardImage(index, item.image_url))
    })
    let totalNum = this.m_questionCard_All.length
    if(totalNum>6 && totalNum<=8) {
      this.m_questionCard_All.forEach(item=>{
        item.ref.setScaleXY(this.g_mapScale * 0.8)
      })
    }
    if(totalNum>8) {
      this.m_questionCard_All.forEach(item=>{
        item.ref.setScaleXY(this.g_mapScale * 0.7)
      })
    }
    this.m_questionCard_All = this.randomArray_shuffle(this.m_questionCard_All)

    this.alignCenter(this.m_questionCard_All, 0, true)

  }
  
  createQuestionCardImage(index, data){
    let element = this.g_cartoon.createCartoonElementImageFunc("question-container-image-"+index, "bg_container_question_card", (w, h)=>{
      return{
        sx: 202 * this.g_mapScale / w,
        sy: 177 * this.g_mapScale / h
      }
    }, (w, h)=>{
      return{
        x: 0,
        y: this.g_cartoon.getOrigin().y + (388 + 161 / 2) * this.g_mapScale
      }
    })

    let highLight = this.g_cartoon.createCartoonElementImageFunc("question-highlight-image-"+index, "bg_xuanbian", (w, h)=>{
      return{
        sx: 202 * 0.95 / w,
        sy: 177 * 0.95 / h
      }
    }, (w, h)=>{
      return{
        x: 0,
        y: 0
      }
    })
    highLight.index = index
    highLight.ref.visible = false;
    element.ref.addChild(highLight.ref)
    this.m_highLight_All.push(highLight)

    let defauBG = this.g_cartoon.createCartoonElementImageFunc("question-container-bg-image-"+index, "bg_xuandi", (w, h)=>{
      return{
        sx: 202 / w,
        sy: 177 / h
      }
    }, (w, h)=>{
      return{
        x: 0,
        y: 0
      }
    })
    element.ref.addChild(defauBG.ref)

    let defauBG_2 = this.g_cartoon.createCartoonElementImageFunc("question-container-bg-image-"+index, "bg_xuan2di", (w, h)=>{
      return{
        sx: 202 / w,
        sy: 177 / h
      }
    }, (w, h)=>{
      return{
        x: 0,
        y: 0
      }
    })
    element.ref.addChild(defauBG_2.ref)

    let image = this.g_cartoon.createCartoonElementImageFunc("questioncard-image-"+index, data, (w, h)=>{
      let s = Math.min(155 / w, 125 / h)
      return{
        sx: s,
        sy: s
      }
    }, (w, h)=>{
      return{
        x: -6,
        y: 0
      }
    })
    element.ref.addChild(image.ref)

    let image_2 = this.g_cartoon.createCartoonElementImageFunc("questioncard-image-"+index, data, (w, h)=>{
      let s = Math.min(155 / w, 125 / h)
      return{
        sx: s,
        sy: s
      }
    }, (w, h)=>{
      return{
        x: -3,
        y: -3
      }
    })
    element.ref.addChild(image_2.ref)

    let kuang = this.g_cartoon.createCartoonElementImageFunc("question-kuang-image-"+index, "bg_xuan1", (w, h)=>{
      return{
        sx: 202 * 0.95 / w,
        sy: 177 * 0.95 / h
      }
    }, (w, h)=>{
      return{
        x: 0,
        y: 0
      }
    })
    element.ref.addChild(kuang.ref)

    let kuang_2 = this.g_cartoon.createCartoonElementImageFunc("question-kuang-image-"+index, "bg_xuan2", (w, h)=>{
      return{
        sx: 202 * 0.95 / w,
        sy: 177 * 0.95 / h
      }
    }, (w, h)=>{
      return{
        x: 0,
        y: 0
      }
    })
    element.ref.addChild(kuang_2.ref)

    element.index = index;
    element.startPos = { x:element.initX, y:element.initY }
    element.backTo = (pos?, callback?)=>{
      if(pos){
        tweenChange(element.ref, pos, 0.1, ()=>{
          callback && callback()
        })
      }else{
        tweenChange(element.ref, { x: this.g_cartoon.getCartoonElement("question-container-image-"+index).initX, y:  this.g_cartoon.getCartoonElement("question-container-image-"+index).initY }, 0.3, ()=>{
          callback && callback()
        })
      }
    }

    element.disable = false;
    element.release = (pos, callback?)=>{
      this.m_enableCardMove = false;
      this.m_currentSelectedCardID = null;
      this.disableMoveAsstant()
      element.backTo(pos, callback)
    }

    element.setStyle = (type) => {
      if(type==1) {
        defauBG.ref.visible = true;
        kuang.ref.visible = true;
        image.ref.visible = true;
        defauBG_2.ref.visible = false;
        kuang_2.ref.visible = false;
        image_2.ref.visible = false;
      } else {
        defauBG.ref.visible = false;
        kuang.ref.visible = false;
        image.ref.visible = false;
        defauBG_2.ref.visible = true;
        kuang_2.ref.visible = true;
        image_2.ref.visible = true;
      }
    }
    element.setStyle(1)

    this.subscribeMapDownEvent(element.id, ()=>{
      if(element.disable){
        this.g_enableMapDown = true;
        return
      }
      this.g_cartoon.playAudio("xuanxiang")
      this.m_enableCardMove = true;
      this.m_currentSelectedCardID = element.id
      this.topOfRenderArray(element.ref)
      this.m_highLight_All.forEach(sel=>{
        if(sel.index == index) {
          sel.ref.visible = true;
        } else {
          sel.ref.visible = false;
        }
      })
      element.startPos = {
        x: this.g_clickX,
        y: this.g_clickY
      }
      this.enableMoveAsstant(()=>{
        element.ref.x = this.g_clickX
        element.ref.y = this.g_clickY
      })
      this.g_enableMapDown = true;
    })

    this.subscribeMapUpEvent(element.id, ()=>{
      if(element.disable){
        this.g_enableMapUp = true;
        return
      }
      element.release()
      this.g_enableMapUp = true;
    })


    this.render(element.ref, zIndexMap.questionCard)
    return element
  }

  // 答案卡片 图片
  initAnsterCard_Image(){
    this.g_formData.dataArray.forEach((element, index) => {
      this.m_answerCard_All.push(this.createAnswerCardImage(index, element))
    });
    this.alignCenter(this.m_answerCard_All, 20*this.g_mapScale, true)
  }

  createAnswerCardImage(index, data){
    let element  = this.g_cartoon.createCartoonElementImageFunc("answercard-image-"+index, "bg_kuang", (w, h)=>{
      return{
        sx: (134 * this.g_mapScale) / w,
        sy: (141 * this.g_mapScale) / h
      }
    }, (w, h)=>{
      return{
        x: 0,
        y: this.g_cartoon.getOrigin().y + 567 * this.g_mapScale + 141/2 * this.g_mapScale
      }
    })
    element.index = index;

    element.shake = (callback?)=>{
      rotateItem(element.ref, 10, 0.1, ()=>{
        rotateItem(element.ref, -10, 0.2, ()=>{
          rotateItem(element.ref, 10, 0.2, ()=>{
            rotateItem(element.ref, 0, 0.1, ()=>{
              callback && callback()
            })
          })
        })
      })
    }

    element.star = (callback?)=>{
      element.starAni = this.g_cartoon.createAnimation("icon_star", 18, 400, ()=>{
        element.starAni.visible = false;
        this.deleteElementInRender(element.starAni.id)
        callback && callback()
      })
      element.starAni.setScaleXY(this.g_mapScale)
      element.starAni.x = element.ref.x
      element.starAni.y = element.ref.y
      this.render(element.starAni, zIndexMap.animation)
      element.starAni.play()
    }

    this.subscribeMapUpEvent(element.id, ()=>{
      if(this.m_currentSelectedCardID && this.m_enableCardMove){
        let selectedCard = this.g_cartoon.getCartoonElement(this.m_currentSelectedCardID)
        if(selectedCard.index == element.index){
          this.m_highLight_All.forEach(sel=>{
            sel.ref.visible = false;
          })
          selectedCard.ref.x = element.ref.x
          selectedCard.ref.y = element.ref.y
          selectedCard.release({x:element.ref.x, y:element.ref.y - 6 * this.g_mapScale}, ()=>{
            this.alignCenter(this.m_answerCard_All, 5*this.g_mapScale, true, ()=>{
              element.star(()=>{
                let end = true
                this.m_answerCard_All.forEach(item=>{
                  if(item.id.indexOf("answercard")!=-1){
                    end = false
                  }
                })
                if(end){
                  this.endGame()
                }
                this.g_cartoon.getCartoonElement("background-main-cat").stepUp()
              })
            })
          })
          selectedCard.disable = true;
          selectedCard.setStyle(2)
          let index = this.m_answerCard_All.indexOf(element)
          this.m_answerCard_All.splice(index, 1, selectedCard)
          this.deleteElementInRender(element.id)

          this.g_cartoon.stopAudio("excellent")
          this.g_cartoon.playAudio("excellent")
        }else{
          selectedCard.release()
          this.disableMoveAsstant();
          element.shake();

          this.g_cartoon.stopAudio("cuowu")
          this.g_cartoon.playAudio("cuowu")
        }
      }
      this.g_enableMapUp = true;
      return true
    }, 100)

    this.render(element.ref, zIndexMap.answerCard)
    return element
  }

  initQuestionBackground(){
    if(this.g_formData.question.type=="LongAudio"){
      let element  = this.g_cartoon.createCartoonElementImageFunc("question-audio-bg", "bg_kuang2", (w, h)=>{
        return{
          sx: this.g_cartoon.getCartoonElement("background-main-desk").ref.scaleX,
          sy: this.g_cartoon.getCartoonElement("background-main-desk").ref.scaleY
        }
      }, (w, h)=>{
        return{
          x: this.g_canvasWidth / 2,
          y: this.g_cartoon.getOrigin().y + 127 * this.g_mapScale
        }
      })
  
      this.render(element.ref, zIndexMap.questionKuang)
    }else{
      let element  = this.g_cartoon.createCartoonElementImageFunc("question-text-image-bg", "bg_kuang1", (w, h)=>{
        return{
          sx: this.g_cartoon.getCartoonElement("background-main-desk").ref.scaleX,
          sy: this.g_cartoon.getCartoonElement("background-main-desk").ref.scaleY
        }
      }, (w, h)=>{
        return{
          x: this.g_canvasWidth / 2,
          y: this.g_cartoon.getOrigin().y + 225 * this.g_mapScale
        }
      })
  
      this.render(element.ref, zIndexMap.questionKuang)
    }
  }
  
  initQuestion(){
    if(this.g_formData.question.type == "LongAudio" &&  this.g_formData.question.longAudio_url != ""  ){
      let element  = this.g_cartoon.getCartoonElement("background-question-audio")
      this.g_cartoon.getCartoonElement("background-question-image-text").ref.visible = false;
      this.g_cartoon.getCartoonElement("background-question-image-text").ref.setScaleXY(0)
    }else{
      let element  = this.g_cartoon.getCartoonElement("background-question-image-text")
      this.g_cartoon.getCartoonElement("background-question-audio").ref.visible = false;
      this.g_cartoon.getCartoonElement("background-question-audio").ref.setScaleXY(0)

      if(this.g_formData.question.type == "Text"){
        let text = this.g_cartoon.createLabel(this.g_formData.question.text, "MMTextBook-Bold", "#fae0a3", 40)
        text.maxSingalLineWidth = 520
        text.textAlign = "left"
        text.refreshSize()
        text.x = -240
        text.y = -431 / 2

        element.ref.addChild(text)
      }else{
        let image = this.g_cartoon.createImage(this.g_formData.question.image_url, (w, h)=>{
          let sx = 590 * 0.9 / w
          let sy = 360 * 0.9 / h
          let s = Math.min(sx, sy)
          return {
            sx: s,
            sy: s
          }
        }, (w, h)=>{
          return {
            x: 0,
            y: -5
          }
        })
        element.ref.addChild(image)
      }
    }
  }

  initWellDone() {
    let element  = this.g_cartoon.createCartoonElementImageFunc("well-done", "bg_welldone", (w, h)=>{
      return{
        sx: 505 * this.g_mapScale / w,
        sy: 343 * this.g_mapScale / h
      }
    }, (w, h)=>{
      return{
        x: this.g_canvasWidth / 2,
        y: this.g_canvasHeight / 2
      }
    })
    element.ref.visible = false;
    element.ref.setScaleXY(0)

    let start1 = this.g_cartoon.createCartoonElementImageFunc("well-done-star-1", "icon_star3", (w, h)=>{
      return{
        sx: 102 / w,
        sy: 99 / h
      }
    }, (w, h)=>{
      return{
        x: -205,
        y: -25
      }
    })
    element.ref.addChild(start1.ref)

    let start2 = this.g_cartoon.createCartoonElementImageFunc("well-done-star-2", "icon_star2", (w, h)=>{
      return{
        sx: 78 / w,
        sy: 74 / h
      }
    }, (w, h)=>{
      return{
        x: 215,
        y: 150
      }
    })
    element.ref.addChild(start2.ref)

    element.popup = (callback?) => {
      element.ref.visible = true;
      tweenChange(element.ref, {scaleX: element.initScaleX, scaleY: element.initScaleY}, 0.3, ()=>{
        tweenChange(start1.ref, {scaleX: start1.initScaleX * 1.3, scaleY: start1.initScaleY * 1.3}, 0.3, ()=>{
          tweenChange(start1.ref, {scaleX: start1.initScaleX, scaleY: start1.initScaleY}, 0.3)
        })
        tweenChange(start2.ref, {scaleX: start2.initScaleX * 1.3, scaleY: start2.initScaleY * 1.3}, 0.3, ()=>{
          tweenChange(start2.ref, {scaleX: start2.initScaleX, scaleY: start2.initScaleY}, 0.3)
        })
        callback && callback()
      })
    }

    this.render(element.ref, 1000)
  }
  






















































  // --------------------------------------------------
  // --------------  Template function  ---------------
  // --------------------------------------------------
  // --------------------------------------------------
  // --------------------------------------------------
  // 
  //                                  _________
  //                                 /         /.
  //           .-------------.      /_________/ |
  //         /             / |      |         | |
  //        /+============+\ |      | |====|  | |
  //        ||C:\>        || |      |         | |
  //        ||            || |      | |====|  | |
  //        ||            || |      |   ___   | |
  //        ||            || |      |  |166|  | |
  //        ||            ||/@@@    |   ---   | |
  //        \+============+/    @   |_________|./.
  //                          @          ..  ....'
  //        ..................@     __.'.'  ''
  //      /oooooooooooooooo//     ///
  //      /................//     /_/
  //      ------------------
  //
  // --------------------------------------------------

  @ViewChild("canvas", {static: true}) canvas: ElementRef;
  @ViewChild("wrap", {static: true}) wrap: ElementRef;
  @HostListener("window:resize", ["$event"])
  onResize(event) {
    this.g_winResizeEventStream.next();
  }
  ngOnDestroy() {
    window["curCtx"] = null;
    window.cancelAnimationFrame(this.g_animationId);
  }
  ngOnInit() {
    const getData = (<any>window).courseware.getData;
    getData(data => {
      // if (window['air'].airClassInfo.user.classRole == 'tea') {
      //   if(!this.g_ForceChangeDefaultRole){
      //     this.g_teacherFlag = true;
      //   }
      // }
      // this.g_currentUser = window['air'].airClassInfo.user;
      if (data && typeof data == "object") {
        this.g_data = data;
        this.g_formData = data.contentObj;
      } else {
        this.g_data = {};
      }

      
      if (!this.g_data.contentObj) {
        this.g_data.contentObj = {};
        this.g_formData = {};
      }

      this.initDefaultData();
      this.initAudio();
      this.initImg();

       // 预加载资源
       this.g_cartoon.loadResources().then(() => {
        window["air"].hideAirClassLoading(this.g_KEY, this.g_data);
        this.initSystem();
        this.update();
        this.systemReady()
      });

      this.initListener();
    }, this.g_KEY);
  }

  // ----------------------------------
  // 初始化默认数据
  // ----------------------------------
  initDefaultData() {
    if ( Object.keys(this.g_formData).length===0 ) {
      this.g_formData = defauleFormData;
    }
  }


  // ----------------------------------
  // 初始化音乐
  // ----------------------------------
  initAudio() {
    const contentObj = this.g_formData;
    if (!contentObj) {
      return;
    }
    // 添加用户上传音效
    let images:Array<string> = this.mapToAduioArray(contentObj)
    images.forEach(image => {
      this.g_cartoon.addAudio( image, image );
    });

    // 添加本地音效
    for( var key in localAudios ){
      this.g_cartoon.addAudio( key, localAudios[key] );
    }
  }

  // ----------------------------------
  // 初始化图片
  // ----------------------------------
  initImg() {
    const contentObj = this.g_formData;
    if (contentObj) {
      const addPicUrl = url => {
        if (url) {
          this.g_cartoon.addImage(url, url);
        }
      };
      let images:Array<string> = this.mapToImageArray(contentObj)
      images.forEach(image => {
        addPicUrl(image)
      });
    }
    // 添加本地图片
    for( var key in localImages ){
     this.g_cartoon.addImage( key, localImages[key] );
    }
  }


  mapDown(event) {
    let myStopPropagation = false;
    if (!this.g_enableMapDown) {
      return;
    }

    this.m_mapDownArray.forEach((item)=>{
      if(!myStopPropagation){
        if (this.checkClickTarget(this.g_cartoon.getCartoonElementRef(item.id))) {
          this.g_enableMapDown = false;
          if(item.callback()){
            myStopPropagation = true;
          }
        }
      }
    })


  }

  mapMove(event) {
    let myStopPropagation = false;
    if (!this.g_enableMapMove) {
      return;
    }

    this.m_mapMoveArray.forEach((item)=>{
      if(!myStopPropagation){
        if (this.checkClickTarget(this.g_cartoon.getCartoonElementRef(item.id))) {
          this.g_enableMapMove = false;
          if(item.callback()){
            myStopPropagation = true;
          }
        }
      }
    })
  }

  mapUp(event) {
    let myStopPropagation = false;
    if (!this.g_enableMapUp) {
      return;
    }
    // for(let cartoonID in this.m_mapUpQueue){
    //   if (this.checkClickTarget(this.g_cartoon.getCartoonElementRef(cartoonID))) {
    //     this.g_enableMapUp = false;
    //     this.m_mapUpQueue[cartoonID]();
    //   }
    // }
    this.m_mapUpArray.forEach((item)=>{
      if(!myStopPropagation){
        if (this.checkClickTarget(this.g_cartoon.getCartoonElementRef(item.id))) {
          this.g_enableMapUp = false;
          if(item.callback()){
            myStopPropagation = true;
          }
        }
      }
    })

  }


  update() {
    this.g_animationId = window.requestAnimationFrame(this.update.bind(this));
    // 清除画布内容
    this.g_ctx.clearRect(0, 0, this.g_canvasWidth, this.g_canvasHeight);
    TWEEN.update();
    this.updateArr(this.m_renderArr);
    this.updateArr(this.m_endPageArr);
    this.updateArr(this.m_elementPetalArr);
  }


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


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


  initListener() {
    const element = this.canvas.nativeElement;
    this.g_winResizeEventStream.pipe(debounceTime(500)).subscribe(data => {
      this.renderAfterResize();
    });
    
    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);
    };

    const touchDownFunc = (e) => {
      if (this.g_firstTouch) {
        this.g_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 (this.g_firstTouch) {
        this.g_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 setMxMyByTouch = event => {
      if (event.touches.length <= 0) {
        return;
      }
      if (this.g_canvasLeft == null) {
        setParentOffset();
      }
      this.g_clickX = event.touches[0].pageX - this.g_canvasLeft;
      this.g_clickY = event.touches[0].pageY - this.g_canvasTop;
    };

    const setParentOffset = () => {
      const rect = this.canvas.nativeElement.getBoundingClientRect();
      this.g_canvasLeft = rect.left;
      this.g_canvasTop = rect.top;
    };

    const setMxMyByMouse = (event) => {
      this.g_clickX = event.offsetX;
      this.g_clickY = event.offsetY;
    };

    addMouseListener();
    addTouchListener();
  }

  showArr(arr) {
    if (!arr) {
      return;
    }
    for (let i = 0; i < arr.length; i++) {
      arr[i].visible = true;
    }
  }

  hideArr(arr) {
    if (!arr) {
      return;
    }
    for (let i = 0; i < arr.length; i++) {
      arr[i].visible = false;
    }
  }

  IsPC() {
    if (window["ELECTRON"]) {
      return false; // 封装客户端标记
    }
    if (
      document.body.ontouchmove !== undefined &&
      document.body.ontouchmove !== undefined
    ) {
      return false;
    } else {
      return true;
    }
  }

  renderAfterResize() {
    this.g_canvasWidth = this.wrap.nativeElement.clientWidth;
    this.g_canvasHeight = this.wrap.nativeElement.clientHeight;
    this.update();
    this.handleScreenResize()
  }

  checkClickTarget(target) {
    if (!target) {
      return false;
    }
    const rect = target.getBoundingBox();
    if (this.checkPointInRect(this.g_clickX, this.g_clickY, 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;
  }


  getPosByAngle(angle, len) {
    const radian = (angle * Math.PI) / 180;
    const x = Math.sin(radian) * len;
    const y = Math.cos(radian) * len;
    return { x, y };
  }


  getPosDistance(sx, sy, ex, ey) {
    const _x = ex - sx;
    const _y = ey - sy;
    const len = Math.sqrt(Math.pow(_x, 2) + Math.pow(_y, 2));
    return len;
  }


  subscribeMapDownEvent(id,callback, zIndex?){
    zIndex = zIndex?zIndex:0
    this.m_mapDownObject.push({id:id, zIndex:zIndex?zIndex:1, callback:callback})
    this.m_mapDownObject.sort((a,b)=>{
      return b.zIndex-a.zIndex
    })
    this.m_mapDownArray = []
    this.m_mapDownObject.forEach(item=>{
      this.m_mapDownArray.push(item)
    })
  }

  subscribeMapUpEvent(id,callback, zIndex?){
    zIndex = zIndex?zIndex:0
    this.m_mapUpObject.push({id:id, zIndex:zIndex?zIndex:1, callback:callback})
    this.m_mapUpObject.sort((a,b)=>{
      return b.zIndex-a.zIndex
    })
    this.m_mapUpArray = []
    this.m_mapUpObject.forEach(item=>{
      this.m_mapUpArray.push(item)
    })
  }

  subscribeMapMoveEvent(id, callback, zIndex?){
    zIndex = zIndex?zIndex:0
    this.m_mapMoveObject.push({id:id, zIndex:zIndex?zIndex:1, callback:callback})
    this.m_mapMoveObject.sort((a,b)=>{
      return a.zIndex - b.zIndex
    })
    this.m_mapMoveArray = []
    this.m_mapMoveObject.forEach(item=>{
      this.m_mapMoveArray.push(item)
    })
  }


  // 全局初始化入口，当资源加载完毕后执行
  initSystem() {
    
    this.g_canvasWidth = this.wrap.nativeElement.clientWidth;
    this.g_canvasHeight = this.wrap.nativeElement.clientHeight;

    const sx = this.g_canvasWidth / this.g_canvasBaseW;
    const sy = this.g_canvasHeight / this.g_canvasBaseH;
    const s = Math.min(sx, sy);

    this.g_mapScale = s;
    this.g_cartoon.mapScale = this.g_mapScale;
    this.g_cartoon.clientWidth = this.wrap.nativeElement.clientWidth;
    this.g_cartoon.clientHeight = this.wrap.nativeElement.clientHeight;

    this.m_renderArr = [];
    this.m_renderObject = [];
    this.g_enableMapDown = true;

    this.g_ctx = this.canvas.nativeElement.getContext("2d");
    this.canvas.nativeElement.width = this.g_canvasWidth;
    this.canvas.nativeElement.height = this.g_canvasHeight;
    window["curCtx"] = this.g_ctx;

    // 初始化舞台
    this.initStage();
    this.update();
  }
  

  initStage() {
    const bgWidth = 1280;
    const bgHeight = 720;
    this.g_cartoon.stageWidth = bgWidth*this.g_mapScale;
    this.g_cartoon.stageHeight= bgHeight*this.g_mapScale;

    const imageColor = this.g_cartoon.createCartoonElement("background-color", "ShapeRect").ref;
    // console.log( "stageWidth: " + this.g_cartoon.stageWidth + " stageHeight" + this.g_cartoon.stageHeight)
    // console.log( "clientWidth: " + this.g_cartoon.clientWidth + " clientHeight" + this.g_cartoon.clientHeight)
    // console.log( "canvasWidth: " + this.g_canvasWidth + " canvasHeight" + this.g_canvasHeight)
    // console.log( "mapScale: " + this.g_mapScale )
    imageColor.x = this.g_cartoon.clientWidth / 2 ;
    imageColor.y = this.g_cartoon.clientHeight / 2 ;
    imageColor.setSize(this.g_cartoon.clientWidth, this.g_cartoon.clientHeight);
    imageColor.init();
    imageColor.fillColor = this.g_background_color;
    this.render(imageColor, -999999)

    const image = this.g_cartoon.createCartoonElement("bg_1280_720_Ruler", "MySprite").ref;
    image.init(this.g_cartoon.images.get("_bg_1280_720_Ruler"));
    image.x = this.g_canvasWidth / 2;
    image.y = this.g_canvasHeight /2;
    image.visible = this.g_EnableStageRuler
    this.g_cartoon.setOrigin( image.x-(bgWidth/2*this.g_mapScale), image.y-(bgHeight/2*this.g_mapScale)  )
    this.g_cartoon.setRelativeOrigin( -bgWidth/2, -bgHeight/2)
    image.setScaleXY(this.g_mapScale);
    this.render(image, 50)
    this.g_stage = image

    const maskLayer = this.g_cartoon.createCartoonElement("_mask_layer_1280_720", "MySprite").ref;
    maskLayer.init(this.g_cartoon.images.get("_mask_layer_1280_720"));
    maskLayer.scaleX = this.g_canvasWidth / maskLayer.width;
    maskLayer.scaleY = this.g_canvasHeight / maskLayer.height;
    maskLayer.alpha = 0
    maskLayer.x = this.g_canvasWidth / 2;
    maskLayer.y = this.g_canvasHeight /2;
    maskLayer.show = (time=0.3, callback?)=>{
      tweenChange(maskLayer, {alpha: 1}, time, ()=>{
        callback && callback()
      })
    }
    maskLayer.hide = (time=0.3, callback?)=>{
      tweenChange(maskLayer, {alpha: 0}, time, ()=>{
        callback && callback()
      })
    }
    this.render(maskLayer, this.g_maskLayerZindex)
  }

  showMaskLayer(time=0.3, callback?) {
    this.g_cartoon.getCartoonElement("_mask_layer_1280_720").ref.show(time, callback)
  }

  hideMaskLayer(time=0.3, callback?) {
    this.g_cartoon.getCartoonElement("_mask_layer_1280_720").ref.hide(time, callback)
  }

  render(ele, zIndex?:number){
    this.m_renderObject.push({element:ele, zIndex:zIndex?zIndex:1})
    this.m_renderObject.sort((a,b)=>{
      return a.zIndex - b.zIndex
    })
    this.m_renderArr = []
    this.m_renderObject.forEach(item=>{
      this.m_renderArr.push(item.element)
    })    
  }

  sendServerEvent(key, data) {
    const c = (<any> window).courseware;
    c.sendEvent(key, JSON.stringify(data));
  }

  addServerListener(msg_key, callback) {
    const c = (<any> window).courseware;
    c.onEvent(msg_key, (data,next) => {
      callback(JSON.parse(data))
      next && next();
    });
  }

  randomArray_shuffle(array) {
    var input = array;
    for (var i = input.length-1; i >=0; i--) {
        var randomIndex = Math.floor(Math.random()*(i+1));
        var itemAtIndex = input[randomIndex];
        input[randomIndex] = input[i];
        input[i] = itemAtIndex;
    }
    return input;
  }

  paginationArray(pageNo, pageSize, array) {
    var offset = (pageNo - 1) * pageSize;
    return (offset + pageSize >= array.length) ? array.slice(offset, array.length) : array.slice(offset, offset + pageSize);
  }

  stopAllTimeout(){
    this.m_setTimeoutIDs.forEach(id=>clearTimeout(id))
    this.m_setTimeoutIDs = []
  }

  stopAllInterval(){
    this.m_setIntervalIDs.forEach(id=>clearInterval(id))
    this.m_setIntervalIDs = []
  }

  topOfRenderArray(element){
    let index = this.m_renderArr.indexOf(element)
    if(index !=-1){
      this.m_renderArr.splice(index, 1)
      this.m_renderArr.push(element)
    }   
  }

  setRenderZIndex(element, zIndex){
    let index = null;
    for(let i=0; i<this.m_renderObject.length; i++){
      if( this.m_renderObject[i].element.id == element.id ){
        index = i
      }
    }
    if(index){
      this.m_renderObject.splice(index, 1)
      this.m_renderObject.push({element:element, zIndex:zIndex?zIndex:1})
      this.m_renderObject.sort((a,b)=>{
        return a.zIndex - b.zIndex
      })
  
      this.m_renderArr = []
      this.m_renderObject.forEach(item=>{
        this.m_renderArr.push(item.element)
      })
    }
  }
  
  deleteElementInRender(id){
    let index = null;
    for(let i=0; i<this.m_renderObject.length; i++){
      if( this.m_renderObject[i].element.id == id ){
        index = i
      }
    }
    if(index){
      this.m_renderObject.splice(index, 1)
      this.m_renderObject.sort((a,b)=>{
        return a.zIndex - b.zIndex
      })
      this.m_renderArr = []
      this.m_renderObject.forEach(item=>{
        this.m_renderArr.push(item.element)
      })
    }else{
      console.warn("Can not found element id:" + id)
    }
  }

  enableMoveAsstant(callback){
    if(this.m_moveAsstantIntervalId){
      clearInterval(this.m_moveAsstantIntervalId)
    }
    this.m_moveAsstantIntervalId = setInterval(()=>{
      callback()
    },50)
  }

  disableMoveAsstant(){
    clearInterval(this.m_moveAsstantIntervalId)
  }

  cleanSystemVar(){
    this.m_mapDownQueue = {}
    this.m_mapDownArray = []
    this.m_mapDownObject = []
    this.m_mapMoveArray = []
    this.m_mapMoveObject = []
    this.m_mapUpQueue = {}
    this.m_mapUpArray = []
    this.m_mapUpObject = []
    this.stopAllInterval();
    this.stopAllTimeout()
    this.g_cartoon.stopAllAudio()
  }

  getMaxSubstringLength(str){
    let maxLength = 0;
    let subSubstring = str.split(" ")
    for (let index=0; index<subSubstring.length; index++) {
      if(subSubstring[index].length > maxLength){
        maxLength = subSubstring[index].length;
      }
    }
    return maxLength
  }

  setLeftCornerTest(){
    const bgRect = new ShapeRect();
    bgRect.setSize(57, 65);
    bgRect.fillColor = '#f8c224';
    const sx = this.g_canvasWidth / this.g_canvasBaseW;
    bgRect.setScaleXY(sx);
    bgRect.x = 65 * sx;
    this.g_partTitle_x = bgRect.x
    this.g_mainTitle_x = bgRect.x + 80 * sx
    bgRect.alpha = 0.5
    this.render(bgRect, 9999);
  }

  alignCenter(elementArray, spacing, withAni?, callback?){
    let totlaWidth = 0
    let length = elementArray.length
    elementArray.forEach(element => {
      let bd = element.ref.getBoundingBox()
      totlaWidth += bd.width
    });
    totlaWidth += (elementArray.length-1) * spacing
    let laseX = this.g_canvasWidth / 2 - totlaWidth/2;
    let baseY= 0;
    elementArray.forEach((element, index) => {
      let bd = element.ref.getBoundingBox();
      if(withAni){
        tweenChange(element.ref, {x: laseX + bd.width / 2}, 0.2, ()=>{
          this.g_cartoon.saveSize(element.id)
          if(length == (index+1)){
            callback && callback()
          }
        })
      }else{
        element.ref.x = laseX + bd.width / 2
        this.g_cartoon.saveSize(element.id)
        if(length == (index+1)){
          callback && callback()
        }
      }

      laseX = (laseX + bd.width + spacing)
    });
  }

  createTestLine(x, y, color?){
    var colorAll = ['#ff0000','#eb4310','#f6941d','#fbb417','#ffff00','#cdd541','#99cc33','#3f9337','#219167','#239676','#24998d','#1f9baa','#0080ff','#3366cc','#333399','#003366','#800080','#a1488e','#c71585','#bd2158'];
    color = color ? color : colorAll[Math.floor(Math.random()*20)]
    this.render(this.g_cartoon.createRectangula({
      width: 5,
      height: 100,
      x: x,
      y: y,
      fillColor: color
    }), 9999)
  }













  













  












  // --------------------------------------------------
  // --------------  Template function  ---------------
  // --------------------------------------------------
  // --------------------------------------------------
  // --------------------------------------------------
  // 
  //                .-~~~~~~~~~-._       _.-~~~~~~~~~-.
  //            __.'              ~.   .~              `.__
  //          .'//                  \./                  \\`.
  //        .'//                     |                     \\`.
  //      .'// .-~"""""""~~~~-._     |     _,-~~~~"""""""~-. \\`.
  //    .'//.-"                 `-.  |  .-'                 "-.\\`.
  //  .'//______.============-..   \ | /   ..-============.______\\`.
  //.'______________________________\|/______________________________`.
  //
  // --------------------------------------------------
  // showParticle( element_id )                 泡泡效果
  // --------------------------------------------------
  // showEndPatal()  /  stopEndPatal()  花瓣飘落结束动画 
  // --------------------------------------------------
  // showCorrectPatal()                 指定元素上面飘花
  // --------------------------------------------------
  // convertPercentToRadian()   将百分比转换为弧长 第一个参数是百分比，第二个参数是方向 true为逆时针，false为顺时针。用于ShapeCircle换圆弧
  // --------------------------------------------------
  // movePaoWuxian()                        元素抛物线跳
  // --------------------------------------------------
  // showJellyAnimation()------------------------------
  // showBlingStar()----------------------显示星星效果--
  // --------------------------------------------------
  


  // 泡泡
  showParticle(card) {
    let myCard = this.g_cartoon.getCartoonElementRelativePosition(card.id)
    showPopParticle(this.g_cartoon.images.get("_bubble"), { x: myCard.x , y: myCard.y }, this.g_stage);
  }

  // 选择正确动画
  showCorrectPatal(card_id, showTime, callback?) {
    this.m_elementPetalArr = [];
    this.m_showElementPetalFlag = true;
    this.addCorrectPetal(card_id);
    setTimeout(()=>{
      this.m_elementPetalArr = [];
      this.m_showElementPetalFlag = false;
      callback && callback()
    },showTime)
  }
  stopAllCorrectPatal(){
    this.m_elementPetalArr = [];
    this.m_showElementPetalFlag = false;
  }

  addCorrectPetal(card_id) {
    if (!this.m_showElementPetalFlag) {
      return;
    }

    let element = this.g_cartoon.getCartoonElement(card_id)
    const petal = new MySprite(this.g_ctx);

    const id = Math.ceil(Math.random() * 3);
    petal.init(this.g_cartoon.images.get(this.m_PetalImage + id));

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

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

    const randomX = Math.random() * element.ref.width * this.g_mapScale;

    petal.x = element.ref.x - (element.ref.width * this.g_mapScale / 2) + randomX;
    petal.y = element.ref.y - (element.ref.height * this.g_mapScale / 2);

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

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

    this.m_elementPetalArr.push(petal);
    moveItem(
      petal,
      petal.x,
      element.ref.y + (element.ref.height * this.g_mapScale / 2),
      petal["time"],
      () => {
        removeItemFromArr(this.m_elementPetalArr, petal);
      }
    );
    rotateItem(petal, petal["tr"], petal["time"]);
    setTimeout(() => {
      this.addCorrectPetal(card_id);
    }, 200);
  }


  // 结束动画花瓣飘落
  showEndPatal() {
    this.m_endPageArr = [];
    this.m_showPetalFlag = true;
    this.addPetal();
  }

  stopEndPatal() {
    this.m_endPageArr = [];
    this.m_showPetalFlag = false;
  }

  addPetal() {
    if (!this.m_showPetalFlag) {
      return;
    }
    const petal = this.getPetal();
    this.m_endPageArr.push(petal);
    moveItem(
      petal,
      petal.x,
      this.g_canvasHeight + petal.height * petal.scaleY,
      petal["time"],
      () => {
        removeItemFromArr(this.m_endPageArr, petal);
      }
    );
    rotateItem(petal, petal["tr"], petal["time"]);
    setTimeout(() => {
      this.addPetal();
    }, 100);
  }

  getPetal() {
    const petal = new MySprite(this.g_ctx);

    const id = Math.ceil(Math.random() * 3);
    petal.init(this.g_cartoon.images.get(this.m_PetalImage + id));

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

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

    const randomX = Math.random() * this.g_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;
  }


  showJellyAnimation(element_id, callback?){
    let element = this.g_cartoon.getCartoonElement(element_id).ref
    tweenChange(element,{ scaleX: this.g_mapScale * 1.2 , scaleY: this.g_mapScale * 1.1 }, 0.1, ()=>{
      tweenChange(element,{ scaleX: this.g_mapScale * 0.8 , scaleY: this.g_mapScale * 0.9 }, 0.1, ()=>{
        tweenChange(element,{ scaleX: this.g_mapScale , scaleY: this.g_mapScale }, 0.1, ()=>{
          callback && callback()
        })
      })
    })
  }

  showShakeAnimation(element_id, callback?){
    let element = this.g_cartoon.getCartoonElement(element_id).ref
    let originX = element.x
    tweenChange(element,{ x: originX - 10*this.g_mapScale }, 0.1, ()=>{
      tweenChange(element,{ x: originX + 10*this.g_mapScale }, 0.1, ()=>{
        tweenChange(element,{ x: originX }, 0.1, ()=>{
          callback && callback()
        })
      })
    })
  }

  convertPercentToRadian(per, direction){
    let radian = 0;
    if(direction) { //逆时针
      if(per*360 > 270){
        radian = 361 - (per*360 - 270)
      }else{
        radian = 270 - per*360
      }
    }else{ //顺时针
      if(per*360 > 90){
        radian = per*360 - 90
      }else{
        radian = 270 + per*360
      }
    }
    return (radian * Math.PI) / 180;
  }

  showBlingStar(element, callback?){
    let rect =  element.getBoundingBox()
    showBlingBling(this.g_cartoon.images.get('icon_star'), rect, element, 0.5, 1, 0.08, 2);
    this.m_setTimeoutIDs.push(setTimeout(() => {
      callback && callback()
    }, 2000))
    // setTimeout(()=>{
    //   showBlingBling(this.g_cartoon.images.get('icon_star'), rect, element, 0.5, 1, 0.08, 1.8);
    // },200)
    // setTimeout(()=>{
    //   showBlingBling(this.g_cartoon.images.get('icon_star'), rect, element, 0.5, 1, 0.08, 1.6);
    // },400)
  }

  movePaoWuxian(element,dis,time,callback?){
    let disX = dis.x - element.x
    let disY = (element.y - dis.y) 
    let count = 0
    let runTime = time/5
    let vx = disX/runTime
    let a = -0.05
    let vy0 = disY/runTime - 0.5*a*runTime
    let id = setInterval(()=>{
      element.x += vx
      element.y -= vy0 + a*count
      count++;
      if(count>runTime){
        clearInterval(id)
        callback && callback()
      }
    }, 5);
  }
}

