const { loadSpine } = require('./utils');

const colorMap = {
    "A": ["#1f356b", "#ffffff", "#bd2c37"],
    "B": ["#fff8d0", "#000000", "#ffb93b"]
}
cc.Class({
    extends: require('BaseUI'),

    properties: {
        dragonBone: dragonBones.ArmatureDisplay,
        skeleton: sp.Skeleton
    },

    onLoad() {
        this._super();
        this.sprImage = this.nodeDict.sprImage.getComponent(cc.Sprite);
        this.labText = this.nodeDict.labText.getComponent(cc.RichText);
        this.labTextTitle = this.nodeDict.labTextTitle.getComponent(cc.RichText);
    },

    init(data, isCover, pageIndex) {
        return new Promise((resolve, reject) => {
            this.data = data;
            this.data.pageType = "spine"
            this.pageIndex = pageIndex;
            this.isCover = isCover;
            this.labText.string = '';
            this.labTextTitle.string = '';

            if (this.data.pageDragonBone.animType == 'spine') {
                this.loadSpineAnim().then(() => {
                    resolve('');
                })
            } else {
                this.loadDragonBoneAnim().then(() => {
                    resolve('');
                })
            }

        });
    },
    stopSpine() {
        if (this._aniSpine) {
            const skeleton = this.skeleton;
            skeleton.clearTracks();
        }
        if (this._aniDragonBone) {
            this._aniDragonBone.stop();
        }
    },
    playSpine() {
        return new Promise((resolve, reject) => {
            if (this.data.pageDragonBone.animType == 'spine') {
                const skeleton = this.skeleton;
                skeleton.setToSetupPose();
                setTimeout(() => {
                    this._aniSpine = skeleton.setAnimation(0, this.animationName, false);
                    skeleton.setCompleteListener(() => {
                        this._aniSpine = null;
                        GameData.isPlaying = 0;
                        resolve('');
                    })
                }, 1);
            } else {
                this._aniDragonBone = this.dragonBone.playAnimation(this.animationName, 1);
                this.dragonBone.on(dragonBones.EventObject.COMPLETE, (evt) => {
                    this._aniDragonBone = null;
                    GameData.isPlaying = 0;
                    resolve('');
                });
            }
        });
    },

    playAudio() {
        if (this.data.pageAudio) {
            cc.assetManager.loadRemote(this.data.pageAudio, null, (err, clip) => {
                this.audioID = cc.audioEngine.play(clip, false, 1);
                this.audioDuration = cc.audioEngine.getDuration(this.audioID);
            });
        }
    },
    stopAudio() {
        cc.audioEngine.stop(this.audioID);
        this.unschedule(this.chengeTextColor);
        GameData.isPlaying = 0;
    },
    loadBg() {
        let url = this.data.pageImage;
        if (!url) return;
        cc.assetManager.loadRemote(url, (error, texture) => {
            if (error) {
                console.log(error)
            }
            this.sprImage.spriteFrame = new cc.SpriteFrame(texture);
            this.setBgScale();
        })
    },

    loadSpineAnim() {

        return new Promise((resolve, reject) => {

            const tex = this.data.pageDragonBone.texPngData.url;
            const atlas = this.data.pageDragonBone.texJsonData.url;
            const ske = this.data.pageDragonBone.skeJsonData.url;

            loadSpine(this.skeleton, this.data.pageDragonBone.texPngData.name, { tex, atlas, ske }).then(({ width, height }) => {
                this.skeleton.node.width = width;
                this.skeleton.node.height = height;

                resolve('');
                this.animationName = this.skeleton.animationNames[0];
                console.log('width: ', this.skeleton.node.width);
                console.log('height~~~: ', this.skeleton.node.height);
                console.log('this.skeleton.node: ', this.skeleton.node);

                this.setSpineScale(this.skeleton.node, this.skeleton.node);
            })
        });

    },
    loadDragonBoneAnim() {
        return new Promise((resolve, reject) => {
            var imageUrl = this.data.pageDragonBone.texPngData.url;
            var skeUrl = this.data.pageDragonBone.skeJsonData.url;
            var atlasUrl = this.data.pageDragonBone.texJsonData.url;
            cc.assetManager.loadAny([{ url: atlasUrl, ext: '.txt' }, { url: skeUrl, ext: '.txt' }], (error, assets) => {
                if (error) return resolve('');
                if (imageUrl == '') console.log(this.data)
                cc.assetManager.loadRemote(imageUrl, (error, texture) => {
                    if (error) return resolve('');
                    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 resolve('');
                    this.dragonBone.armatureName = data.name;
                    this.animationName = data.animation[0].name;
                    this.dragonBone.animationName = this.animationName;

                    // this.dragonBone.premultipliedAlpha = true;
                    // atlas.texture.setPremultiplyAlpha(true);

                    console.log('data.canvas:', data.canvas);

                    this.setSpineScale(data.canvas, this.dragonBone.node);
                    return resolve('');
                });
            });
        });

    },
    // 缩放
    setBgScale() {
        let bgWidth = 382;
        let bgHeight = 540;
        if (this.nodeDict.sprImage.width != bgWidth || this.nodeDict.sprImage.height != bgHeight) {
            let designScale = bgWidth / bgHeight;
            let scale = this.nodeDict.sprImage.width / this.nodeDict.sprImage.height;
            if (scale > designScale) {
                this.nodeDict.sprImage.scale = bgWidth / this.nodeDict.sprImage.width;
            } else {
                this.nodeDict.sprImage.scale = bgHeight / this.nodeDict.sprImage.height;
            }
        }
    },
    setSpineScale(size, node) {
        // return;
        if (!size) {
            return;
        }
        // let bgWidth = 482;
        // let bgHeight = 489;
        let bgWidth = 460;
        let bgHeight = 464;
        if (size.width != bgWidth || size.height != bgHeight) {
            let designScale = bgWidth / bgHeight;
            let scale = size.width / size.height;
            if (scale > designScale) {
                node.scale = bgWidth / size.width;
            } else {
                node.scale = bgHeight / size.height;
            }
        }
    },
    // update (dt) {},
});
