import { asyncDelay, onHomeworkFinish } from "../script/util";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {
    @property(cc.Node)
    dragonBoneNode: cc.Node = null;
    @property(cc.Node)
    btnPlay: cc.Node = null;
    @property(cc.Node)
    aniInfo: cc.Node = null;
    @property(cc.Node)
    outlineBorder: cc.Node = null;

    addPreloadImage() {
        // TODO 根据自己的配置预加载图片资源
        this._imageResList.push({ url: this.data.pic_url });
        this._imageResList.push({ url: this.data.pic_url_2 });
    }

    addPreloadAudio() {
        // TODO 根据自己的配置预加载音频资源
        this._audioResList.push({ url: this.data.audio_url });
    }

    addPreloadAnima() {

    }

    async onLoadEnd() {
        // TODO 加载完成后的逻辑写在这里, 下面的代码仅供参考
        this.initGlobal();
        this.loadDragonBoneAnim();
    }




    dragonDisplay = null;
    initGlobal() {
        // 初始化播放按钮
        this.btnPlay.on("click", ()=>{
            this.playDragBone(this.currentPlayAniName)
        })

        // 初始化骨骼动画
        this.dragonDisplay = this.dragonBoneNode.getComponent(dragonBones.ArmatureDisplay);
    }
    
    
    currentAniData = null;
    currentPlayAniName = null;
    canvas = null;
    loadDragonBoneAnim() {
        let dbData = {
            tex_png_url: "http://teach.cdn.ireadabc.com/a3f250a588c6c3e80683a00e9aa95e5d.png",
            ske_json_url: "http://teach.cdn.ireadabc.com/e9193257f9158cdb0b655fa2c5554512.json",
            tex_json_url: "http://teach.cdn.ireadabc.com/a97b1a41e874cc3ac56ed13106ee4a09.json",
        }

        const queryData = this.getQueryString("data");
        if(queryData) {
            dbData = JSON.parse(decodeURIComponent(queryData))
        }
        console.log(dbData)
        const canvas = cc.find("Canvas")
        return new Promise((resolve, reject) => {
            cc.assetManager.loadAny([{ url: dbData.tex_json_url, ext: '.txt' }, { url: dbData.ske_json_url, ext: '.txt' }], (error, assets) => {
                if (error) return resolve('');
                if (dbData.tex_png_url == '') console.log(this.data)
                cc.assetManager.loadRemote(dbData.tex_png_url, (error, texture) => {
                    if (error) return resolve('');
                    var atlas = new dragonBones.DragonBonesAtlasAsset();
                    atlas.atlasJson = assets[0];
                    atlas.texture = texture;

                    var asset = new dragonBones.DragonBonesAsset();
                    asset.dragonBonesJson = assets[1];
                    this.dragonDisplay.dragonAtlasAsset = atlas;
                    this.dragonDisplay.dragonAsset = asset;

                    let data = asset._dragonBonesJsonData.armature[0];
                    if (!data) return resolve('');
                    console.log(data)
                    this.currentAniData = data;

                    this.dragonDisplay.armatureName = data.name;
                    this.currentPlayAniName = data.animation[0].name;
                    this.dragonDisplay.animationName = this.currentPlayAniName;
                    
                    const scaleX = canvas.width / data.canvas.width;
                    const scaleY = (canvas.height - 150) / data.canvas.height;
                    const scale = Math.min(scaleX, scaleY);
                    this.dragonBoneNode.scale = scale;
                    this.outlineBorder.width = data.canvas.width;
                    this.outlineBorder.height = data.canvas.height;
                    this.outlineBorder.scale = scale;
                    
                    // this.dragonDisplay.premultipliedAlpha = true;
                    // atlas.texture.setPremultiplyAlpha(true);
                    this.updateDragonBoneInfo(this.currentAniData)
                    
                    return resolve('');
                });
            });
        });
    }

    createAniSelectButtons(buttonNames) {
        const template = cc.find("Canvas/aniSelBtn")
        const parent = cc.find("Canvas/btnSelAniGroup");
        buttonNames.forEach((btnName, index) => {
            const node = cc.instantiate(template);
            node.getComponent(cc.Label).string = "播放:" + btnName;
            node.on("click", ()=>{
                this.playDragBone(btnName);
                this.currentPlayAniName = btnName;
            })
            node.x = index * 150
            node.active = true;
            parent.addChild(node);
        });
    }

    getQueryString(name) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = window.location.search.substr(1).match(reg);
        if (r != null) {
            return unescape(r[2]);
        }
        return null;
    }

    updateDragonBoneInfo(data) {
        let richtext = this.aniInfo.getComponent(cc.RichText);
        let allAniNAme = [];
        data.animation.forEach(ani => {
            allAniNAme.push(ani.name)
        });

        this.createAniSelectButtons(allAniNAme);
        
        // 默认播放
        let defaultPlayAniName = null;
        if(data.defaultActions && data.defaultActions.length>0) {
            defaultPlayAniName = data.defaultActions[0].gotoAndPlay;
        }

        let templateStr = `<span>名称: ${data.name}</span>  <span>默认播放:${defaultPlayAniName}</span>    <span>帧率: ${data.frameRate}fps</span><br/>`;
        templateStr += `<span>宽:${data.aabb.width}</span>    <span>高:${data.aabb.height}</span>    <span>画布宽:${data.canvas.width}</span>    <span>画布高:${data.canvas.height}</span>    <span>中心点x:${data.canvas.x}</span>    <span>中心点y:${data.canvas.y}</span><br/>`;
        richtext.string = templateStr;
    }

    playDragBone(aniName) {
        this.dragonDisplay.playAnimation(aniName, 1);
    }

    playLocalAudio(audioName) {
        const audio = cc.find(`Canvas/res/audio/${audioName}`).getComponent(cc.AudioSource);
        return new Promise((resolve, reject) => {
            const id = cc.audioEngine.playEffect(audio.clip, false);
            cc.audioEngine.setFinishCallback(id, () => {
                resolve(id);
            });
        })
    }
}
