const tools = require("../script/tools");

cc.Class({
    extends: cc.Component,

    properties: {
        label: cc.Label,
        playAnim: cc.Animation
    },

    data: null,

    onEnable() {
    },

    onDisable() {

    },

    initWithData(data) {
        this.data = data
        let rect = this.data.rect
        console.log(rect)
        this.node.x = rect.x + rect.width / 2
        this.node.y = -rect.y - rect.height / 2
        this.node.width = rect.width
        this.node.height = rect.height
        this.node.scale = data.fontScale ? data.fontScale : 1
        this.label.string = data.text ? data.text : ''
        this.audioId = null
        if (data.audio_url) {
            this.playAnim.node.active = true
        } else {
            this.playAnim.node.active = false
        }
    },

    onTouchStart() {
        if (this.audioId) return
        if (this.data) {
            let url = this.data.audio_url
            if (url && url != '') {
                this.playAudio(url)
            }
            this.playAnim.play('play')
        }
    },

    /** 播放音乐 */
    playAudio(url) {
        cc.assetManager.loadRemote(url, (err, audioClip) => {
            if (err) return
            cc.systemEvent.once('stopMusic', this.stopAudio, this)
            this.audioId = cc.audioEngine.play(audioClip, false, 0.8);
            cc.audioEngine.setFinishCallback(this.audioId, this.stopAudio.bind(this));
        });
    },

    stopAudio() {
        if (this.audioId != null) {
            cc.audioEngine.stop(this.audioId)
            this.audioId = null
            this.playAnim.play('stop')
            cc.systemEvent.off('stopMusic', this.stopAudio, this)
        }
    },
    /** 音频id */
    audioId: null,
});
