import Cartoon from "./Cartoon"
import defaultData from "./defaultData"
import { jelly } from "./utils"

export default class GameLogic {
  g_cartoon = null;
  g_formData = null
  g_enableClick = true;
  g_canvas = null;
  g_systemOption = null;
  g_useDefaultData = false;
  g_curDragonDisplay = null;
  
  m_questionAudioPlayed = false;
  m_currentQuestion = -1;
  m_questionDone = false;
  m_currentQuestionArray = []
  m_gameEnd = false;
  constructor(formData, systemOption) {
    this.g_systemOption = systemOption;
    this.g_canvas = cc.find('Canvas');
    this.g_cartoon = new Cartoon(cc);

    if(!formData.contentObj.dataArray || formData.contentObj.dataArray.length == 0) {
      this.g_useDefaultData = true;
      this.g_formData = defaultData
      console.warn("User default data =>", this.g_formData)
    } else {
      this.g_formData = formData.contentObj;
      console.log("User saved data =>", this.g_formData)
    }
    
    this.g_cartoon.initLocalAudios([
    	"test_audio",
      "bird_fly",
      "enter",
      "good_job",
      "star_boom",
      "try_again"
    ])
    this.g_cartoon.playAudio("enter", ()=>{
      if(this.g_formData.questionAudio_url) {
        this.g_cartoon.playAudio(this.g_formData.questionAudio_url, ()=>{
          this.initBGMusic();
          this.loadQuestion();
        })
      } else {
        this.initBGMusic();
        this.loadQuestion();
      }
      
    })
    
    this.initBg()
    this.initNodes();
    this.resetPosition();
    this.initBottomButtons();
    this.initBirds();
    this.initImageCards();
    this.initTitle();
    

    this.initMaskLayer();
  }

  initNodes() {
  	let dataLength = this.g_formData.dataArray.length;
  	this.g_cartoon.initCartoonElement("title_text", this.g_cartoon.getNodeByPath(`Canvas/title/text`))
    for(let index=0; index<10; index++) {
      const card = this.g_cartoon.initCartoonElement(`card_${index+1}`, this.g_cartoon.getNodeByPath(`Canvas/card_${index+1}`))
      if(index>=dataLength) {
      	card.node.active = false;
      }

      this.g_cartoon.initCartoonElement(`card_${index+1}_normal`, this.g_cartoon.getNodeByPath(`Canvas/card_${index+1}/normal`));
      this.g_cartoon.initCartoonElement(`card_${index+1}_selected`, this.g_cartoon.getNodeByPath(`Canvas/card_${index+1}/selected`));
      this.g_cartoon.initCartoonElement(`card_${index+1}_bell`, this.g_cartoon.getNodeByPath(`Canvas/card_${index+1}/bell`))
      this.g_cartoon.initCartoonElement(`card_${index+1}_bell_text`, this.g_cartoon.getNodeByPath(`Canvas/card_${index+1}/bell/index`))
      this.g_cartoon.initCartoonElement(`card_${index+1}_bell_outline`, this.g_cartoon.getNodeByPath(`Canvas/card_${index+1}/bell/bell_outline`));
      this.g_cartoon.initCartoonElement(`card_${index+1}_image_container`, this.g_cartoon.getNodeByPath(`Canvas/card_${index+1}/container/image`));
    }

    if(dataLength==0) {
    	this.g_cartoon.getNodeByPath(`Canvas/shengzi/line_1`).active = false;
      this.g_cartoon.getNodeByPath(`Canvas/shengzi/line_2`).active = false;
    } else if(dataLength<=5) {
    	this.g_cartoon.getNodeByPath(`Canvas/shengzi/line_2`).active = false;
    }

		this.g_cartoon.initCartoonElement(`bottomButtons`, this.g_cartoon.getNodeByPath(`Canvas/bottomButtons`));
    this.g_cartoon.initCartoonElement(`restart_button`, this.g_cartoon.getNodeByPath(`Canvas/bottomButtons/restart`));

    this.g_cartoon.initCartoonElement(`bird_1`, this.g_cartoon.getNodeByPath(`Canvas/bird_1`));
    this.g_cartoon.initCartoonElement(`bird_2`, this.g_cartoon.getNodeByPath(`Canvas/bird_2`));
    this.g_cartoon.initCartoonElement(`birdAudio`, this.g_cartoon.getNodeByPath(`Canvas/bgMain/bird_audio`));

  }

  initBg() {
    const bgNode = cc.find('Canvas/bgMain/bg');
    const bgNodeSnow = cc.find('Canvas/bgMain/bg_snow');
    const tree1 = cc.find('Canvas/bgMain/tree_1');
    const tree2 = cc.find('Canvas/bgMain/tree_2/1')
    const tree3 = cc.find('Canvas/bgMain/tree_2/2')

    bgNode.scale = this.g_systemOption.mapScaleMax;
    bgNodeSnow.width = cc.winSize.width
    tree1.height = cc.winSize.height
    tree2.height = cc.winSize.height
    tree3.height = cc.winSize.height
  }

  initBGMusic() {
  	if(this.g_formData.bgMusic) {
			this.g_cartoon.playAudio(this.g_formData.bgMusic).then(audioID => {
        cc.audioEngine.setLoop(audioID, true);
        cc.audioEngine.setVolume(audioID, 0.3);
			})
  	}
  }

  resetPosition() {
    const bgNodeTitle= cc.find('Canvas/title');
    const bgNodeSnow = cc.find('Canvas/bgMain/bg_snow');
    const bgNodeShuicao = cc.find('Canvas/bgMain/shuicao');
    bgNodeTitle.y = cc.winSize.height / 2 - bgNodeTitle.height / 2 - 50
    bgNodeSnow.y = -cc.winSize.height / 2 + bgNodeSnow.height / 2
    bgNodeShuicao.y = -cc.winSize.height / 2 + bgNodeShuicao.height / 2

    const cardPos = [
  		{x: -500, y: 128}, {x: -250, y: 128}, {x: 0, y: 128}, {x: 250, y: 128}, {x: 500, y: 128},
  		{x: -500, y: -114}, {x: -250, y: -114}, {x: 0, y: -114}, {x: 250, y: -114}, {x: 500, y: -114}
  	]

		for(let index=0; index<10; index++) {
      const card = this.g_cartoon.getCartoonElement(`card_${index+1}`)
      card.node.setPosition(cardPos[index].x, cardPos[index].y)
    }
  }

  initImageCards() {
  	let dataLength = this.g_formData.dataArray.length;
    if(dataLength == 0) {
      return 
    }
    let newIndex = [0];
    if(dataLength!=1) {
      newIndex = this.getRandomArray(dataLength)
    }

    this.m_currentQuestionArray = []
    for(let index=0; index<dataLength; index++) {
    	this.m_currentQuestionArray.push(index)
    }

  	for (let index = 0; index<dataLength; index++) {
      let dataItem = this.g_formData.dataArray[newIndex[index]];
      let card = this.g_cartoon.getCartoonElement(`card_${index+1}`)
      card.open = false;

      let cardNormal = this.g_cartoon.getCartoonElement(`card_${index+1}_normal`)
      let cardSelected = this.g_cartoon.getCartoonElement(`card_${index+1}_selected`)
      let imageContainer = this.g_cartoon.getCartoonElement(`card_${index+1}_image_container`)
      imageContainer.cardIndex = index;
      imageContainer.correctIndex = newIndex[index];

      let bellOutline = this.g_cartoon.getCartoonElement(`card_${index+1}_bell_outline`)
      let bellText = this.g_cartoon.getCartoonElement(`card_${index+1}_bell_text`)
      bellText.node.getComponent(cc.Label).font = this.g_cartoon.getFontFamily("Comic Sans MS")
    	bellText.node.getComponent(cc.Label).fontSize = 20

      card.playAudio = (callback) => {
        if(dataItem.audio_url) {
          this.g_cartoon.playAudio(dataItem.audio_url, ()=>{
            if(callback) {
              callback()
            }
          })
        } else {
          if(callback) {
            callback()
          }
        }
      }

      if(this.g_useDefaultData || !dataItem) {
        let fr = this.getSpriteFrimeByResName("card_demo")
        imageContainer.node.setScale(1)
        imageContainer.node.getComponent(cc.Sprite).spriteFrame = fr
      } else {
        this.getSpriteFrimeByUrl(dataItem.image_url, (fr)=>{
          let sx = 220 / fr.getRect().width;
          let sy = 110 / fr.getRect().height;
          let s = Math.min(sx, sy)
          imageContainer.node.width = s * fr.getRect().width;
          imageContainer.node.height = s * fr.getRect().height;
          imageContainer.node.getComponent(cc.Sprite).spriteFrame = fr
        })
      }

      bellOutline.node.setScale(0);

      this.g_cartoon.subscribeTouchEvent(`card_${index+1}_image_container`, ()=>{
      	if(card.open || this.m_gameEnd || !this.g_enableClick) {
      		return;
      	}
        this.g_enableClick = false;
        if(this.m_currentQuestion == imageContainer.correctIndex ) {
          this.g_cartoon.playAudio("good_job")
        	card.open = true;
        	this.g_cartoon.getCartoonElement(`card_${imageContainer.cardIndex+1}_normal`).node.opacity = 0;
			    this.g_cartoon.getCartoonElement(`card_${imageContainer.cardIndex+1}_selected`).node.opacity = 255;
			    this.g_cartoon.getCartoonElement("bird_2").flyTo(imageContainer.cardIndex, ()=>{
			    	this.switchCard(this.m_currentQuestion, imageContainer.cardIndex, ()=>{
              this.g_enableClick = true;
              this.loadQuestion()
            })
			    })
        } else {
          this.g_cartoon.playAudio("try_again", ()=>{
            setTimeout(()=>{
              this.g_cartoon.playAudio(this.g_formData.dataArray[this.m_currentQuestion].audio_url)
              this.g_enableClick = true;
            }, 1000)
          })
        }
      })

      card.tweenHandle = null;
      const runBell = () => {
      	bellOutline.node.setScale(1, 1)
      	bellOutline.node.opacity = 255;
      	card.tweenHandle = this.g_cartoon.tweenChange(bellOutline.node, {scaleX: 2, scaleY: 2, opacity: 0}, 0.4, ()=>{
      		runBell()
      	})
      }

      const stopBell = () => {
      	if(card.tweenHandle) {
      		card.tweenHandle.stop();
      		card.tweenHandle = null
      	}
      	bellOutline.node.setScale(0, 0)
      	bellOutline.node.opacity = 0;
      }

      this.g_cartoon.subscribeTouchEvent(`card_${index+1}_bell`, ()=>{
        if(dataItem.audio_url) {
          this.g_cartoon.stopAllAudio()
          card.playAudio(()=>{
            stopBell()
          })
          runBell()
        }
      })
    }
  }

  switchCard(fromIndex, toIndex, callback) {
    let i1 = this.m_currentQuestionArray[fromIndex]+1;
    let i2 = this.m_currentQuestionArray[toIndex]
    let card_1 = this.g_cartoon.getCartoonElement(`card_${i1}`)
    let card_2 = this.g_cartoon.getCartoonElement(`card_${toIndex+1}`)
    // console.log("交换",`card_${i1}`,`card_${toIndex+1}`)
    let x_1 = card_1.node.x
    let y_1 = card_1.node.y
    let x_2 = card_2.node.x
    let y_2 = card_2.node.y
    
    card_1.node.setSiblingIndex(10);
    card_2.node.setSiblingIndex(10);

 		let bell1 = this.g_cartoon.getCartoonElement(`card_${i1}_bell`)
    let bell2 = this.g_cartoon.getCartoonElement(`card_${toIndex+1}_bell`)
    this.g_cartoon.tweenChange(bell1.node, {scaleX: 0, scaleY: 0}, 0.2, ()=>{
    	this.g_cartoon.tweenChange(card_1.node, {x: x_2, y: y_2}, 1, ()=>{
	    	this.g_cartoon.tweenChange(bell1.node, {scaleX: 1, scaleY: 1}, 0.2);
	    });
    });

    this.g_cartoon.tweenChange(bell2.node, {scaleX: 0, scaleY: 0}, 0.2, ()=>{
    	this.g_cartoon.tweenChange(card_2.node, {x: x_1, y: y_1}, 1, ()=>{
	    	this.g_cartoon.tweenChange(bell2.node, {scaleX: 1, scaleY: 1}, 0.2, ()=>{
	    		this.g_cartoon.getCartoonElement("bird_1").flyBack(()=>{
	    			setTimeout(()=>{
	    				if(callback) {
			    			callback();
			    		}
			    	}, 1500)
	    		})
	    		this.g_cartoon.getCartoonElement("bird_2").flyBack()
	    	});
	    });
    });
    
		let bellText1 = this.g_cartoon.getCartoonElement(`card_${i1}_bell_text`)
    let bellText2 = this.g_cartoon.getCartoonElement(`card_${toIndex+1}_bell_text`)
    toIndex = this.getCurrentIndex(toIndex)
    bellText1.node.getComponent(cc.Label).string = "" + (toIndex+1)
    bellText2.node.getComponent(cc.Label).string = "" + (fromIndex+1)

    let temp = this.m_currentQuestionArray[fromIndex]
    this.m_currentQuestionArray[fromIndex] = this.m_currentQuestionArray[toIndex]
    this.m_currentQuestionArray[toIndex] = temp;
  }

  getCurrentIndex(index) {
    return this.m_currentQuestionArray.indexOf(index)
  }

  initTitle() {
		let textNode = this.g_cartoon.getCartoonElement("title_text")
    let fontSize = 36
    if(this.g_formData.titleText.length>=32 && this.g_formData.titleText.length<48) {
      fontSize = 26
    } else if(this.g_formData.titleText.length>=48) {
      fontSize = 20
    }
    console.log("fontSize", fontSize)
    textNode.node.getComponent(cc.Label).string = this.g_formData.titleText;
		textNode.node.getComponent(cc.Label).font = this.g_cartoon.getFontFamily("Comic Sans MS")
    textNode.node.getComponent(cc.Label).fontSize = fontSize

    textNode.audioID = null
    this.g_cartoon.subscribeTouchEvent(textNode.key, ()=>{
      if(textNode.audioID) {
        cc.audioEngine.stop(textNode.audioID);
        textNode.audioID = null
      }
      this.g_cartoon.playAudio(this.g_formData.questionAudio_url).then((audio_id) =>{
        textNode.audioID = audio_id
      })
    })
  }

  getRandomArray(length) {
    Array.prototype.shuffle = function() {
      let m = this.length, i;
      while (m) {
          i = (Math.random() * m--) >>> 0;
          [this[m], this[i]] = [this[i], this[m]]
      }
      return this;
    }
    
    const gameLogicCheck = (array, startIndex) => {
      let res = true;
      for(let index=startIndex; index<array.length; index++) {
        let changeIndex = array.indexOf(index)
        if(array[index]==index) {
          res = false
          break;
        }
      }
      return res;
    }

    let indexArray = []
    for(let index=0; index<length; index++) {
      indexArray.push(index)
    }
    var arr = indexArray.shuffle()
    var result = false;
    var temp = null;
    var count = 0;
    var arrayCanUse = []
    do{
      result = false;
      arr = indexArray.shuffle()
      arrayCanUse = JSON.parse(JSON.stringify(arr))

      for(let index=0; index<arr.length; index++) {
        if(index==arr[index]) {
          result = true;
          break
        }
      }
    
      if(!result) {
        for(let index=0; index<arr.length-2; index++) {
          var indexChange = arr.indexOf(index)
          temp = arr[index]
          arr[index] = index;
          arr[indexChange] = temp;
          if(!gameLogicCheck(arr, index+1)) {
            result = true;
            break
          }
        }

      }
      if(count>20000) {
        console.log("已经尝试超过两万次，终止生成", arr)
        result = false
      }
    } while(result)

    return arrayCanUse
  }

  loadQuestion() {
    let index = null;
    let dataLength = this.g_formData.dataArray.length;
    for(let i=0; i<10; i++) {
      this.g_cartoon.getCartoonElement(`card_${i+1}_normal`).node.opacity = 255;
      this.g_cartoon.getCartoonElement(`card_${i+1}_selected`).node.opacity = 0;
    }
    this.m_currentQuestion++;
    if((this.m_currentQuestion+1)==dataLength) {
    	this.endGame()
    } else {
    	index = this.m_currentQuestionArray[this.m_currentQuestion]
    	this.g_cartoon.getCartoonElement("bird_1").flyTo(index, ()=>{
        this.g_cartoon.playAudio(this.g_formData.dataArray[this.m_currentQuestion].audio_url)
      })
	    this.g_cartoon.getCartoonElement(`card_${index+1}_normal`).node.opacity = 0;
	    this.g_cartoon.getCartoonElement(`card_${index+1}_selected`).node.opacity = 255;
    }
  }

  endGame() {
  	this.m_gameEnd = true;
  	let resetBtn = this.g_cartoon.getCartoonElement("restart_button")
  	resetBtn.node.active = true;
  }

  restartGame(callback) {
  	this.m_questionAudioPlayed = false;
	  this.m_currentQuestion = -1;
	  this.m_questionDone = false;
	  this.m_currentQuestionArray = []
	  this.m_gameEnd = false;
		for(let index=0; index<10; index++) {
      const card = this.g_cartoon.getCartoonElement(`card_${index+1}`)
    }
  	this.g_cartoon.stopAllAudio()
    this.showMaskLayer(()=>{
    	this.resetPosition();
    	this.initImageCards();
	    this.initTitle();
	    this.loadQuestion();
      this.hideMaskLayer(()=>{ 
        if(callback) {
          callback()
        }
      })
    })
  }

  initBottomButtons() {
  	let bottomButtons = this.g_cartoon.getCartoonElement("bottomButtons")
  	bottomButtons.node.x = cc.winSize.width / 2 - 100
  	bottomButtons.node.y = -cc.winSize.height / 2 + 50

  	let resetBtn = this.g_cartoon.getCartoonElement("restart_button")
  	resetBtn.node.active = false;

  	this.g_cartoon.subscribeTouchEvent(resetBtn.key, ()=>{
  		jelly(resetBtn.node).then(()=>{
  			resetBtn.node.active = false;
  		})
			this.restartGame()
  	})

  }

  initBirds() {
  	let bird_1 = this.g_cartoon.getCartoonElement("bird_1");
  	let bird_2 = this.g_cartoon.getCartoonElement("bird_2");
    let birdAudio = this.g_cartoon.getCartoonElement("birdAudio");

  	bird_1.flyTo = (cardIndex, callback)=>{
  		let card = this.g_cartoon.getCartoonElement(`card_${cardIndex+1}`)
 
  		const worldPos = cc.find("Canvas").convertToWorldSpaceAR(cc.v2(bird_1.node.x, bird_1.node.y));
			const localPos = card.node.convertToNodeSpaceAR(cc.v2(worldPos.x, worldPos.y));

			bird_1.node.x = localPos.x;
  		bird_1.node.y = localPos.y;
  		bird_1.node.parent = card.node;

  		this.g_cartoon.tweenChange(bird_1.node, {x: -80, y: 90}, 0.5, ()=>{
  			if(callback) {
  				callback()
  			}
  		})
  	}

  	bird_1.flyBack = (callback)=>{
  		let parent = bird_1.node.parent
  		const worldPos = parent.convertToWorldSpaceAR(cc.v2(bird_1.node.x, bird_1.node.y));
			const localPos = cc.find("Canvas").convertToNodeSpaceAR(cc.v2(worldPos.x, worldPos.y));
			bird_1.node.x = localPos.x;
  		bird_1.node.y = localPos.y;
  		bird_1.node.parent = cc.find("Canvas");

  		this.g_cartoon.tweenChange(bird_1.node, {x: -100, y: -cc.winSize.height / 2 + bird_2.node.height + 10}, 0.5, ()=>{
  			if(callback) {
  				callback()
  			}
  		})
  	}

  	bird_2.flyTo = (cardIndex, callback)=>{
  		let card = this.g_cartoon.getCartoonElement(`card_${cardIndex+1}`)
 
  		const worldPos = cc.find("Canvas").convertToWorldSpaceAR(cc.v2(bird_2.node.x, bird_2.node.y));
			const localPos = card.node.convertToNodeSpaceAR(cc.v2(worldPos.x, worldPos.y));

			bird_2.node.x = localPos.x;
  		bird_2.node.y = localPos.y;
  		bird_2.node.parent = card.node;

  		this.g_cartoon.tweenChange(bird_2.node, {x: 80, y: 90}, 0.5, ()=>{
  			if(callback) {
  				callback()
  			}
  		})
  	}

  	bird_2.flyBack = (callback)=>{
  		let parent = bird_2.node.parent
  		const worldPos = parent.convertToWorldSpaceAR(cc.v2(bird_2.node.x, bird_2.node.y));
			const localPos = cc.find("Canvas").convertToNodeSpaceAR(cc.v2(worldPos.x, worldPos.y));
			bird_2.node.x = localPos.x;
  		bird_2.node.y = localPos.y;
  		bird_2.node.parent = cc.find("Canvas");

  		this.g_cartoon.tweenChange(bird_2.node, {x: 105, y: -cc.winSize.height / 2 + bird_2.node.height}, 0.5, ()=>{
  			if(callback) {
  				callback()
  			}
  		})
  	}

    bird_1.node.y = -cc.winSize.height / 2 + bird_1.node.height + 10
    bird_2.node.y = -cc.winSize.height / 2 + bird_2.node.height
    birdAudio.node.y = -cc.winSize.height / 2 + bird_2.node.height + 20
    birdAudio.audioID = null
    bird_1.node.setSiblingIndex(20);
    bird_2.node.setSiblingIndex(20);

    this.g_cartoon.subscribeTouchEvent(birdAudio.key, ()=>{
      if(birdAudio.audioID) {
        cc.audioEngine.stop(birdAudio.audioID);
        birdAudio.audioID = null;
        birdAudio.node.getChildByName("play").opacity = 255;
      }

      if(this.g_formData.dataArray[this.m_currentQuestion].audio_url) {
        birdAudio.node.getChildByName("play").opacity = 0;
        this.g_cartoon.playAudio(this.g_formData.dataArray[this.m_currentQuestion].audio_url, ()=>{
          birdAudio.node.getChildByName("play").opacity = 255;
        }).then(audio_id=>{
          birdAudio.audioID = audio_id
        })
      }
    })
  }













	initCenterImage() {
    let imageContainer = this.g_cartoon.getCartoonElement("center_image_container")
    if(!this.g_formData.dataArray[this.m_currentQuestion].question.centerImage_url) {
      let fr = this.getSpriteFrimeByResName("default_stage")
      imageContainer.node.setScale(1)
      imageContainer.node.getComponent(cc.Sprite).spriteFrame = fr
    } else {
      let parentWidth = imageContainer.node.parent.width
      let parentHeight = imageContainer.node.parent.height
      this.getSpriteFrimeByUrl(this.g_formData.dataArray[this.m_currentQuestion].question.centerImage_url, (fr)=>{
        imageContainer.node.getComponent(cc.Sprite).spriteFrame = fr
        imageContainer.node.scaleX = parentWidth / imageContainer.node.width
        imageContainer.node.scaleY = parentHeight / imageContainer.node.height
      })
    } 
  }

  initQuestionPannel() {
    let title = this.g_cartoon.getCartoonElement("question_title_pannel")
    let body = this.g_cartoon.getCartoonElement("question_body_pannel")
    let bodyText = this.g_cartoon.getCartoonElement("question_body_pannel_text")

    this.g_cartoon.subscribeTouchEvent(title.key, ()=>{
      if(!this.g_enableClick) {
        console.warn("g_enableClick disabeld!")
        return;
      }
      if(this.g_formData.dataArray[this.m_currentQuestion].question.question_audio_url) {
        this.g_cartoon.stopAllAudio()
        this.g_cartoon.playAudio(this.g_formData.dataArray[this.m_currentQuestion].question.question_audio_url, ()=>{

        })
      }
    })

    body.in = (callback) => {
      body.node.y = -cc.winSize.height / 2 - this.g_cartoon.getCartoonElement("question_body_pannel_background").node.height / 2
      this.g_cartoon.tweenChange(body.node, {y: -270}, 0.5, ()=>{
        this.g_cartoon.tweenChange(bodyText.node, {opacity: 255}, 0.5, ()=>{
          if(callback) {
            callback()
          }
        })
      })
    }

    body.out = () => {
      bodyText.node.opacity = 0;
      body.node.y = -cc.winSize.height / 2 - this.g_cartoon.getCartoonElement("question_body_pannel_background").node.height / 2
    }

    this.g_cartoon.subscribeTouchEvent(body.key, ()=>{
      if(!this.g_enableClick) {
        console.warn("g_enableClick disabeld!")
        return;
      }
      
      if(this.g_formData.dataArray[this.m_currentQuestion].question.body_audio_url) {
        this.g_cartoon.stopAllAudio()
        this.g_cartoon.getCartoonElement("Text_DragonBones").dragonBones.showDragonBones(1)
        this.g_cartoon.playAudio(this.g_formData.dataArray[this.m_currentQuestion].question.body_audio_url, ()=>{

        })
      }
    })
  }

  initDragonBonesContainer () {
    let container =  this.g_cartoon.getCartoonElement("DragonBones-Container")

    container.hide = () => {
      // container.node.scaleX = 0
      // container.node.scaleY = 0
      container.node.opacity = 0;
    }

    container.show = (callback) => {
      // container.node.y = container.node.y + 220;
      container.node.opacity = 0;
      this.g_cartoon.tweenChange(container.node, {opacity: 255}, 0.7, ()=>{
        if(callback) {
          callback()
        }
      })
    }
  }

  initSelectedCards() {
    let order = [2,6,3,7,1,5,4,8]
    let dragonBones = this.g_formData.dataArray[this.m_currentQuestion].dragonBones;
    for (let index = 0; index < 8; index++) {
      let dataItem = this.g_formData.dataArray[this.m_currentQuestion].selectCards[index];
      let el = this.g_cartoon.getCartoonElement(`selected_${order[index]}`)
      if(!dataItem) {
        el.node.active = false;
        continue;
      } else {
        el.node.active = true;
      }
    
      this.g_cartoon.getCartoonElement(`selected_${order[index]}_highlight`).node.active = false;
      this.g_cartoon.getCartoonElement(`selected_${order[index]}_play`).node.active = false;

      let audioEl = this.g_cartoon.getCartoonElement(`selected_${order[index]}_speaker`);
      let audioAni = this.g_cartoon.creatSpeaker(audioEl.node, "icon_sound", "icon_sound_2")
      let imageContainer = this.g_cartoon.getCartoonElement(`selected_${order[index]}_image_container`)
      let errorIcon = this.g_cartoon.getCartoonElement(`selected_${order[index]}_error_x`)
      errorIcon.node.scale = 0;
      let errorMask = this.g_cartoon.getCartoonElement(`selected_${order[index]}_error_mask`)
      errorMask.node.active = false;

      if(this.g_useDefaultData) {
        let fr = this.getSpriteFrimeByResName(dataItem.image_url)
        imageContainer.node.getComponent(cc.Sprite).spriteFrame = fr
      } else {
        this.getSpriteFrimeByUrl(dataItem.image_url, (fr)=>{
          imageContainer.node.getComponent(cc.Sprite).spriteFrame = fr
        })
      }
      
      this.g_cartoon.subscribeTouchEvent(el.key, ()=>{
        if(!this.g_enableClick) {
          console.warn("g_enableClick disabeld!")
          return;
        }
        if(this.m_questionDone) {
          return;
        }
        this.g_enableClick = false;
        if(dataItem.isAnswer) {
          this.maskOthers(order[index]-1)
          this.g_cartoon.getCartoonElement(`selected_${order[index]}_highlight`).node.active = true;
          this.g_cartoon.playAudio("right_goodjob")
          this.showRightCircle(imageContainer, ()=>{
            this.m_questionDone = true;
            this.g_enableClick = true;
            if(this.g_formData.dataArray[this.m_currentQuestion].question.body_audio_url) {
              this.g_cartoon.playAudio(this.g_formData.dataArray[this.m_currentQuestion].question.body_audio_url, ()=>{
                this.g_cartoon.playAudio("good_job")
              })
            } else {
              this.g_cartoon.playAudio("good_job")
            }
            if(dragonBones && dragonBones.texPngData.url && dragonBones.skeJsonData.url && dragonBones.texJsonData.url) {
              this.g_cartoon.getCartoonElement("Center_DragonBones").dragonBones.setDragonBones(dragonBones, (handle)=>{
                this.g_cartoon.getCartoonElement("DragonBones-Container").show(()=>{
                  handle.showDragonBones(0);
                }, ()=>{
                  // handle.showDragonBones();
                })
              })
            }
          })
        } else {
          this.showWrongCircle(errorIcon.node, errorMask.node)
          this.g_enableClick = true;
        }
      })

      el.in = (callback) => {
        this.g_cartoon.tweenChange(el.node, {x: el.initX}, 0.5, ()=>{
          callback && callback()
        })
      }

      el.out = (callback) => {
        this.g_cartoon.tweenChange(el.node, {x: el.initX - this.g_canvas.width}, 0.5, ()=>{
          callback && callback()
        })
      }

      el.setContent = (image_url) => {
        this.g_cartoon.tweenChange(imageContainer.node, {scaleX: 0, scaleY: 0}, 0.1, ()=>{
          this.getSpriteFrimeByUrl(image_url, (fr)=>{
            imageContainer.node.getComponent(cc.Sprite).spriteFrame = fr
            this.g_cartoon.tweenChange(imageContainer.node, {scaleX: imageContainer.initScaleX, scaleY: imageContainer.initScaleY}, 0.1)
          })
        })
      }

      if(!dataItem.audio_url) {
        audioEl.node.active = false;
      } else {
        audioEl.node.active = true;
      }

			this.g_cartoon.getCartoonElement(`selected_${order[index]}_speaker`).node.off("click")
      this.g_cartoon.getCartoonElement(`selected_${order[index]}_speaker`).node.on("click", ()=>{
        this.g_cartoon.stopAllAudio()
        this.g_cartoon.stopSoundAnima(audioAni)
        this.g_cartoon.showSoundAnima(audioAni)
        if(!this.m_questionDone) {
          this.g_cartoon.getCartoonElement(`selected_${order[index]}_play`).node.active = true;
        }

        this.g_cartoon.playAudio(dataItem.audio_url, ()=>{
          this.g_cartoon.stopSoundAnima(audioAni)
          this.g_cartoon.getCartoonElement(`selected_${order[index]}_play`).node.active = false;
        })
        
      })

    }
  }

  playQuestion(callback) {
    if(this.m_currentQuestion==0 && this.g_formData.dataArray[this.m_currentQuestion].question.question_audio_url) {
      this.g_cartoon.playAudio(this.g_formData.dataArray[this.m_currentQuestion].question.question_audio_url, ()=>{
        this.m_questionAudioPlayed = true;
        this.g_cartoon.getCartoonElement("question_body_pannel").in(()=>this.playQuestionBody(()=>{
          if(callback) {
            callback()
          }
        }));
      })
    } else {
      this.g_cartoon.getCartoonElement("question_body_pannel").in(()=>this.playQuestionBody(()=>{
        if(callback) {
          callback()
        }
      }));
    }
  }

  playQuestionBody(callback) {
  	console.log("TEST", this.g_formData.dataArray[this.m_currentQuestion].question.body_audio_url)
    if(this.g_formData.dataArray[this.m_currentQuestion].question.body_audio_url) {
      this.g_cartoon.playAudio(this.g_formData.dataArray[this.m_currentQuestion].question.body_audio_url, ()=>{
        if(callback) {
          callback()
        }
      })
    } else {
      if(callback) {
        callback()
      }
    }
  }

  initButtons() {
    let left = this.g_cartoon.getCartoonElement(`buttombutton_left`)
    let right = this.g_cartoon.getCartoonElement(`buttombutton_right`)
    let reload = this.g_cartoon.getCartoonElement(`buttombutton_restart`)
    let close = this.g_cartoon.getCartoonElement(`buttombutton_close`)

    left.disabled = true;
    left.node.opacity = 128;
    right.disabled = false;

    this.g_cartoon.subscribeTouchEvent(left.key, ()=>{
      if(!this.g_enableClick) {
        console.warn("g_enableClick disabeld!")
        return;
      }
      if(left.disabled) {
        return
      }
      this.g_enableClick = false;
      
      jelly(left.node)
      if(this.m_currentQuestion >0) {
        this.m_currentQuestion--
        this.refreshQuestion(()=>{
          this.g_enableClick = true;
        })
      } else {
        this.g_enableClick = true;
      }
    })

    this.g_cartoon.subscribeTouchEvent(right.key, ()=>{
      if(!this.g_enableClick) {
        console.warn("g_enableClick disabeld!")
        return;
      }
      if(right.disabled) {
        return
      }
      jelly(right.node)
      this.g_enableClick = false;
      if(this.m_currentQuestion<this.g_formData.dataArray.length-1) {
        this.m_currentQuestion++
        this.refreshQuestion(()=>{
          this.g_enableClick = true;
        })
      } else {
        this.g_enableClick = true;
      }
    })

    this.g_cartoon.subscribeTouchEvent(reload.key, ()=>{
      if(!this.g_enableClick) {
        console.warn("g_enableClick disabeld!")
        return;
      }
      
      jelly(reload.node)
      this.g_enableClick = false;
      this.refreshQuestion(()=>{
        this.g_enableClick = true;
      })
    })

  }

  maskOthers(index) {
    for(let i=0; i<8; i++) {
      this.g_cartoon.getCartoonElement(`selected_${i+1}_error_mask`).node.active = (index==i)?false:true;
    }
  }

  resetAllSelectedCards() {
    this.m_questionDone = false;
    this.m_questionAudioPlayed = false;
    for(let i=1; i<=8; i++) {
      this.g_cartoon.getCartoonElement(`selected_${i}_highlight`).node.active = false
      this.g_cartoon.getCartoonElement(`selected_${i}_play`).node.active = false
      this.g_cartoon.getCartoonElement(`selected_${i}_image_container`).node.active = true
    }
    this.g_cartoon.getCartoonElement("DragonBones-Container").hide();
    this.g_cartoon.getCartoonElement("question_body_pannel").out();
    // this.g_cartoon.getCartoonElement("question_title_pannel").out()
    this.g_cartoon.getCartoonElement("Center_DragonBones").dragonBones.resetDragonBones()

  }

  initText() {
    this.g_cartoon.getCartoonElement("question_title_pannel_text").node.color = this.g_cartoon.getColor("FFFFFF")
    this.g_cartoon.getCartoonElement("question_title_pannel_text").node.getComponent(cc.Label).string =  this.g_formData.dataArray[this.m_currentQuestion].question.question_text
    this.g_cartoon.getCartoonElement("question_title_pannel_text").node.getComponent(cc.Label).font = this.g_cartoon.getFontFamily("FatMarker")
    this.g_cartoon.getCartoonElement("question_title_pannel_text").node.getComponent(cc.Label).fontSize = 32

    this.g_cartoon.getCartoonElement("question_body_pannel_text").node.color = this.g_cartoon.getColor("ffd75f")
    this.g_cartoon.getCartoonElement("question_body_pannel_text").node.getComponent(cc.Label).string = this.g_formData.dataArray[this.m_currentQuestion].question.body_text
    this.g_cartoon.getCartoonElement("question_body_pannel_text").node.getComponent(cc.Label).font = this.g_cartoon.getFontFamily("BRLNSR_1")
    this.g_cartoon.getCartoonElement("question_body_pannel_text").node.getComponent(cc.Label).fontSize = 42;

    this.g_cartoon.getCartoonElement("question_body_pannel_text").node.active = true;

  }

  checkButtonStatus() {
		if(this.m_currentQuestion == 0) {
      this.g_cartoon.getCartoonElement("buttombutton_left").node.opacity = 128;
      this.g_cartoon.getCartoonElement("buttombutton_left").disabled = true;
    } else {
      this.g_cartoon.getCartoonElement("buttombutton_left").node.opacity = 255;
      this.g_cartoon.getCartoonElement("buttombutton_left").disabled = false;
    }

    if(this.m_currentQuestion == this.g_formData.dataArray.length-1) {
      this.g_cartoon.getCartoonElement("buttombutton_right").node.opacity = 128;
      this.g_cartoon.getCartoonElement("buttombutton_right").disabled = true;
    } else {
      this.g_cartoon.getCartoonElement("buttombutton_right").node.opacity = 255;
      this.g_cartoon.getCartoonElement("buttombutton_right").disabled = false;
    }
  }

  refreshQuestion(callback) {
    this.g_cartoon.stopAllAudio()
    this.showMaskLayer(()=>{
    	this.checkButtonStatus()
      this.resetAllSelectedCards()
      this.initSelectedCards();
      this.initText()
      this.initCenterImage();
      this.hideMaskLayer(()=>{
        this.playQuestion(()=>{
          if(callback) {
            callback()
          }
        })
      })
    })
    
  }

  showRightCircle(targetNode, callback) {
    const centerPic = this.g_cartoon.getNodeByPath(`Canvas/center_image`)
    const oldParent = targetNode.node.parent
    const worldPos = oldParent.convertToWorldSpaceAR(cc.v2(targetNode.node.x, targetNode.node.y));
    const localPos = centerPic.convertToNodeSpaceAR(cc.v2(worldPos.x, worldPos.y));
    const picNode = this.g_cartoon.cloneNode(targetNode.node)
    targetNode.node.active = false;
  
    picNode.parent = centerPic;
    picNode.x = localPos.x;
    picNode.y = localPos.y;
  
    const sx = centerPic.width / picNode.width
    const sy = centerPic.height / picNode.height;
    const s = Math.min(sx, sy);

    cc.tween(picNode)
      .to(0.7, {x: 0, y: 0, angle: 360}, {easing: 'sineOut'})
      .delay(0.2)
      .to(1.5, {scale: s, opacity: 0}, {easing: 'cubicOut'})
      .call(() => {
        if(callback) {
          callback()
        }
      })
      .start();
  }
  
  
  showWrongCircle(icon, mask) {
    if (mask.active) {
      return;
    }
    // cc.audioEngine.play(this.audioWrong.clip, false, 0.2)
  	this.g_cartoon.playAudio("error")
    const showIcon = () => {
      cc.tween(icon)
        .to(0.3, {scale: 0.9}, {easing: 'bounceOut'})
        .delay(0.2)
        .to(0.7, {scale: 0}, {easing: 'cubicIn'})
        .call(()=>{
          this.g_cartoon.playAudio("tryagain")
        })
        .start();
    }
  
    const hide = () => {
      mask.opacity = 0;
      cc.tween(mask)
      .to(0.1, {opacity: 255})
      .call(() => {
        showIcon();
      })
      .start()
    }
  
    hide();
    mask.active = true;
  }










  // Common function
  maskLayer = null;
  initMaskLayer() {
    const parentNode = this.g_cartoon.getNodeByPath("Canvas/MaskLayer")
    parentNode.x = cc.winSize.width / 2
    parentNode.y = cc.winSize.height / 2
    const bNode = this.getSprNode('black');
    bNode.scaleX = cc.winSize.width / bNode.width;
    bNode.scaleY = cc.winSize.height / bNode.height;
    bNode.x = 0
    bNode.y = 0
    parentNode.setSiblingIndex(255)
    bNode.parent = cc.find('Canvas');
    bNode.active = false;
    this.maskLayer = bNode;
  }

  showMaskLayer(cb) {
    this.maskLayer.opacity = 0;
    this.maskLayer.active = true;
    cc.tween(this.maskLayer)
      .to(0.5, {opacity: 255}, {easing: 'sineOut'})
      .call(() => {
        cb()
      })
      .start()
  }

  hideMaskLayer(cb = null) {
    this.maskLayer.opacity = 255;
    cc.tween(this.maskLayer)
    .to(0.5, {opacity: 0}, {easing: 'sineIn'})
    .call(() => {
      this.maskLayer.active = false;
      if (cb) {
        cb()
      }
    })
    .start()
  }





  // Common API
  getSpriteFrimeByUrl(url, cb) {
		cc.assetManager.loadRemote(url, (err, img) => {
			const spriteFrame = new cc.SpriteFrame(img)
			if (cb) {
				cb(spriteFrame);
			}
		})
  }

  getSpriteFrimeByResName(name) {
    const sf = cc.find('Canvas/res/img/' + name).getComponent(cc.Sprite).spriteFrame;
    // const node = new cc.Node();
    // node.addComponent(cc.Sprite).spriteFrame = sf;
    return sf;
  }

  getSprNode(resName) {
    const sf = cc.find('Canvas/res/img/' + resName).getComponent(cc.Sprite).spriteFrame;
    const node = new cc.Node();
    node.addComponent(cc.Sprite).spriteFrame = sf;
    return node;
  }
}
