const Color_texts = ['#BE1AC1', '#24C11A', '#1A1DC1', '#9F5307'];
cc.Class({
    extends: cc.Component,

    properties: {
        dragonBone: dragonBones.ArmatureDisplay,
        sprBg: cc.Sprite,
        nodMask: cc.Node,
        layoutText: cc.Node,
        labWord: cc.Label,
    },


    onEnable() {
        this.node.on('touchend', this.onTouchEnd, this);
    },

    onDisable() {
        this.node.off('touchend', this.onTouchEnd, this);
    },

    onTouchEnd() {
        this.scheduleOnce(() => {
            if (GameData._isPageTurning) {
                return;
            }
            if (this.isPlaying) {
                return;
            }
            this.isPlaying = true;
            // 播放动画
            this.playAudio();
            this.playSpine();
        })
    },
    onLoad() {
        this.anim = this.getComponent(cc.Animation)
    },

    setInfo(data, index) {
        this.index = index;
        this.data = data;
    },

    start() {
        if (this.data.type == 'Image') {
            this.loadBg();
        } else {
            this.loadSpine();
        }
        this.initRichText();
    },

    loadBg() {
        let url = this.data.image_url;
        cc.assetManager.loadRemote(url, (error, texture) => {
            if (error) {
                console.log(error)
            }
            this.sprBg.spriteFrame = new cc.SpriteFrame(texture);
            this.setBgScale();
        })
    },
    loadSpine() {
        if (this.data.type == 'Image') {
            return;
        }
        this.dragonBone.dragonAtlasAsset = null;
        this.dragonBone.dragonAsset = null;
        this.dragonBone.armatureName = '';
        var imageUrl = this.data.tex_png;
        var skeUrl = this.data.ske_json;
        var atlasUrl = this.data.tex_json;
        // imageUrl = 'http://127.0.0.1/walkingfish_tex.png';
        // skeUrl = 'http://127.0.0.1/walkingfish_ske.json';
        // atlasUrl = 'http://127.0.0.1/walkingfish_tex.json';

        // imageUrl = 'http://127.0.0.1/1_tex.png';
        // skeUrl = 'http://127.0.0.1/1_ske.json';
        // atlasUrl = 'http://127.0.0.1/1_tex.json';
        cc.assetManager.loadAny([{ url: atlasUrl, ext: '.txt' }, { url: skeUrl, ext: '.txt' }], (error, assets) => {
            if (error) {
                console.log(error)
            }
            else {
                cc.assetManager.loadRemote(imageUrl, (error, texture) => {
                    if (error) {
                        console.log(error)
                    }
                    else {
                        var atlas = new dragonBones.DragonBonesAtlasAsset();
                        atlas._uuid = atlasUrl;
                        atlas.atlasJson = assets[0];
                        atlas.texture = texture;

                        var asset = new dragonBones.DragonBonesAsset();
                        asset._uuid = skeUrl;
                        asset.dragonBonesJson = assets[1];

                        this.dragonBone.dragonAtlasAsset = atlas;
                        this.dragonBone.dragonAsset = asset;
                        let data = asset._dragonBonesJsonData.armature[0];
                        if (!data) {
                            return;
                        }
                        this.dragonBone.armatureName = data.name;
                        this.animationName = data.animation[0].name;
                        this.dragonBone.animationName = this.animationName;
                        this.dragonBone.premultipliedAlpha = true;
                        atlas.texture.setPremultiplyAlpha(true);
                        this.setSpineScale(data.canvas);
                    }
                });
            }
        });

    },

    // 缩放
    setBgScale() {
        let bgWidth = 1000;
        let bgHeight = 500;
        if (!this.data.text) {
            bgHeight = 546;
        }
        if (this.sprBg.node.width != bgWidth || this.sprBg.node.height != bgHeight) {
            let designScale = bgWidth / bgHeight;
            let scale = this.sprBg.node.width / this.sprBg.node.height;
            if (scale > designScale) {
                this.sprBg.node.scale = bgWidth / this.sprBg.node.width;
            } else {
                this.sprBg.node.scale = bgHeight / this.sprBg.node.height;
            }
        }
    },
    setSpineScale(size) {
        let mask = this.dragonBone.node.parent;
        if (!size) {
            mask.width = 1000;
            mask.height = 500;
            if (!this.data.text) {
                bgHeight = 546;
            }
            this.dragonBone.node.scale = 1;
            return;
        }
        let bgWidth = 1000;
        let bgHeight = 500;
        if (!this.data.text) {
            bgHeight = 546;
        }
        if (size.width != bgWidth || size.height != bgHeight) {
            let designScale = bgWidth / bgHeight;
            let scale = size.width / size.height;
            if (scale > designScale) {
                this.dragonBone.node.scale = bgWidth / size.width;
            } else {
                this.dragonBone.node.scale = bgHeight / size.height;
            }
        }

        mask.width = this.dragonBone.node.scale * size.width;
        mask.height = this.dragonBone.node.scale * size.height;
    },

    // 初始化文本
    initRichText() {
        // this.data.text = 'I am flying';
        this.sprBg.node.y = 40;
        this.dragonBone.node.y = 40;
        if (!this.data.text) {
            this.sprBg.node.y = 0;
            this.dragonBone.node.y = 0;
            return;
        }
        this.data.text = this.data.text.replace(/ /g, " |");
        let arr = this.data.text.split('|');
        if (arr.length <= 0) {
            return;
        }
        this.layoutText.active = true;
        this.labWord.string = arr[0];
        this.labWord._forceUpdateRenderData(true)
        for (let i = 0; i < arr.length - 1; i++) {
            if (arr[i + 1] == ' ') {
                continue;
            }
            let node = cc.instantiate(this.labWord.node);
            node.parent = this.layoutText;
            let label = node.getComponent(cc.Label);
            label.string = arr[i + 1];
            label._forceUpdateRenderData(true);
        }
        this.layoutText.getComponent(cc.Layout).updateLayout();

        let width = this.layoutText.width;
        if (width > 1000) {
            let scale = 1000 / width;
            this.layoutText.scale = scale;
        }
    },

    playAudio() {
        // this.data.shortAudio_url = 'http://127.0.0.1/iamflying.mp3';
        cc.assetManager.loadRemote(this.data.shortAudio_url, null, (err, clip) => {
            this.audioID = cc.audioEngine.play(clip, false, 1);
            this.audioDuration = cc.audioEngine.getDuration(this.audioID);
            this.textDuration = this.audioDuration / this.layoutText.childrenCount;
            this.textIndex = 0;
            this.schedule(this.chengeTextColor, this.textDuration, this.layoutText.childrenCount, 0.01)
        });
        this.playSpine();
    },
    stopAudio() {
        cc.audioEngine.stop(this.audioID);
        this.unschedule(this.chengeTextColor);
        this.isPlaying = false;
        this.stopSpine();
    },
    playSpine() {
        this.dragonBone.playAnimation(this.animationName, 1);
    },
    stopSpine() {
        this.loadSpine();
    },

    chengeTextColor() {
        if (!this.layoutText.children[this.textIndex] || this.textIndex == this.layoutText.childrenCount) {
            this.isPlaying = false;
            this.unschedule(this.chengeTextColor);
        }
        this.layoutText.children[this.textIndex] && (this.layoutText.children[this.textIndex].color = new cc.Color().fromHEX(Color_texts[this.index % 3]));
        this.layoutText.children[this.textIndex - 1] && (this.layoutText.children[this.textIndex - 1].color = new cc.Color().fromHEX(Color_texts[3]));
        this.textIndex++;
    },
    clearTextColor() {
        for (let i = 0; i < this.layoutText.children.length; i++) {
            this.layoutText.children[i].color = new cc.Color().fromHEX(Color_texts[3]);
        }
    },

    // 变为当前页
    onCurrPage() {
        this.clearTextColor();

    },

    playPageUp() {
        this.anim.play('pageUp');
        this.stopAudio();
    },
    playPageDown() {
        this.anim.play('pageDown');
        this.stopAudio();
    },

    showMask() {
        this.nodMask.opacity = 51;
        this.node.angle = -1;
    },
    playShowMask() {
        cc.tween(this.node)
            .to(0.75, { angle: -1 })
            .start()
        cc.tween(this.nodMask)
            .to(0.75, { opacity: 51 })
            .start()
    },
    hideMask() {
        this.nodMask.opacity = 0;
        this.node.angle = 0;
    },
    playHideMask() {
        cc.tween(this.node)
            .to(0.75, { angle: 0 })
            .start()
        cc.tween(this.nodMask)
            .to(0.75, { opacity: 0 })
            .start()
    },

    // update (dt) {},
});
