var playingItem = null

cc.Class({
    extends: cc.Component,

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

    data: null,

    audio_url: null,

    onEnable() {
        cc.systemEvent.on('stopWordsMusic', this.stopAudio, this)
    },

    onDisable() {
        cc.systemEvent.off('stopWordsMusic', this.stopAudio, this)
    },

    initWithData(data, scale) {
        let action = data['actionData_']
        if (!action) {
            this.node.active = false
            return
        } else {
            this.node.action = true
        }
        this.data = data
        let rect = this.data.rect
        this.node.x = (rect.x + rect.width / 2) * scale
        this.node.y = (-rect.y - rect.height / 2) * scale
        this.node.width = rect.width * scale
        this.node.height = rect.height * scale

        let node = this.label.node
        let option = action.changeOption
        node.color = option[0][1] ? cc.color(option[0][1]) : cc.color(0, 0, 0)
        let num = Number(option[1][1]) * scale * data.fontScale
        this.label.fontSize = num
        this.label.lineHeight = num
        this.label.string = action.text ? action.text : ''
        this.audioId = null
        this.audio_url = action.audio_url
        if (this.audio_url) {
            let node = this.playAnim.node
            node.setPosition(this.node.width / 2 + node.width / 2 + 15, (-this.node.height + node.height) / 2)
            node.active = true
        } else {
            this.playAnim.node.active = false
        }
    },

    onTouchStart() {
        if (this.audioId != null) return
        if (this.audio_url && this.audio_url != '') {
            this.playAudio(this.audio_url)
            this.playAnim.play('play')
            cc.systemEvent.emit('stopBgMusic')
        }
    },

    /** 播放音乐 */
    playAudio(url) {
        if (this._playing) {
            this.stopAudio()
            return
        }
        this._playing = true
        cc.assetManager.loadRemote(url, (err, audioClip) => {
            if (err) return
            if (playingItem && playingItem != this) playingItem.stopAudio()
            if (!this._playing) return
            this.audioId = cc.audioEngine.play(audioClip, false, 0.8);
            cc.audioEngine.setFinishCallback(this.audioId, this.stopAudio.bind(this));
            playingItem = this
        });
    },

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