import { asyncDelay, asyncPlayDragonBoneAnimation, getSpriteFrimeByUrl, goNextPage, onHomeworkFinish } from "../script/util_DG22";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent_DG22";
import Boy from "../script/items/boy_DG22";
import DragObj from "../script/items/dragObj_DG22";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {

    @property(cc.Node)
    boyNode = null;
    @property(cc.Node)
    fogeNode = null;

    @property(cc.Node)
    dragObj: cc.Node = null;

    @property(cc.Node)
    itemBg = null;

    @property(cc.Node)
    rect: cc.Node = null;
    @property(cc.Node)
    box = null;

    @property(cc.Node)
    dragRoot: cc.Node = null;

    @property(cc.Node)
    btn_start: cc.Node = null;

    @property(cc.Node)
    btn_restart: cc.Node = null;

    @property(cc.Node)
    btn_end: cc.Node = null;

    @property(cc.Node)
    cover: cc.Node = null;


    bgItemData: any;
    dragData: any;
    _rightIndex: number = 0;
    _totalIndex: any;

    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.start_audio_url });
        this._audioResList.push({ url: this.data.end_audio_url });
    }

    addPreloadAnima() {

    }

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

    _cantouch = null;
    initData() {
        // 所有全局变量 默认都是null 

        cc.log(JSON.stringify(this.data, null, 2))
        this._cantouch = true;
    }

    initView() {
        this.initBg();
        this.initPageData();

        this.boyNode.x = 500;
        this.boyNode.getComponent(Boy).playRun(-1);
        cc.tween(this.boyNode).to(1, { x: 67 }).call(() => {
            this.boyNode.getComponent(Boy).playtalk(-1);
            this.playAudioByUrl(this.data.start_audio_url, () => {
                this.boyNode.getComponent(Boy).playNormal();
                this.btn_start.active = true;
            })

        }).start();

        let list = this.dragRoot.children;
        for (let i = 0; i < list.length; ++i) {
            list[i].active = false;
        }


    }

    startPage() {
        this.btn_start.active = false;
        this.cover.active = false;
        this.btn_restart.active = false;

        this.boyNode.getComponent(Boy).playRun(-1);
        this.boyNode.scaleX = -0.5;
        cc.tween(this.boyNode).to(1, { x: 500 }).call(() => {
            this.node.getChildByName("bgm").active = true;
        }).start();

        this.initPageView();

    }
    restartPage() {
        this.btn_start.active = false;
        this.btn_restart.active = false;
        this.cover.active = false;
        this.btn_end.active = false;
        this.dragRoot.children.forEach((val) => {
            val.removeAllChildren();
        });
        this.rect.removeAllChildren();
        this.boyNode.getComponent(Boy).playtalk(-1);
        this.playAudioByUrl(this.data.start_audio_url, () => {
            this.boyNode.getComponent(Boy).playNormal();
            this.initPageView();
        })

    }
    initBg() {
        const bgNode = cc.find('Canvas/bg');
        bgNode.scale = this._mapScaleMax;
        cc.tween(this.btn_start).to(0.3, { scale: 1.1 }).to(0.2, { scale: 1 }).delay(1).union().repeatForever().start();
        cc.tween(this.btn_restart).to(0.3, { scale: 1.1 }).to(0.2, { scale: 1 }).delay(1).union().repeatForever().start();
        this.btn_restart.active = false;
        this.cover.active = true;
        this.btn_start.on("click", this.startPage, this)
        this.btn_restart.on("click", this.restartPage, this)
        this.btn_start.active = false;

        this.btn_end.active = false;

        this.btn_end.on("click", () => {
            goNextPage();
        }, this)

    }
    initPageData() {
        this._rightIndex = 0;
        this.bgItemData = this.data.questions[0].bgItem;
        this.dragData = this.data.questions[0].hotZoneItemArr;
        this._totalIndex = this.dragData.length;
    }
    initPageView() {
        this.btn_end.scale = 0;
        if (this.data.end_btn_text) {
            this.btn_end.scale = 1;
            this.btn_end.getChildByName("lb").getComponent(cc.Label).string = this.data.end_btn_text;
        }

        if (this.bgItemData.url) {
            getSpriteFrimeByUrl(this.bgItemData.url, (spf) => {
                this.itemBg.getComponent(cc.Sprite).spriteFrame = spf;
                this.itemBg.width = this.bgItemData.rect.width;
                this.itemBg.height = this.bgItemData.rect.height;
                this.rect.getComponent(cc.Widget).updateAlignment();
                this.itemBg.scale = Math.min(680 / this.itemBg.width, 400 / this.itemBg.height)
            })
        }

        let keyMap = new Map();;
        let list = this.dragRoot.children;
        for (let i = 0; i < this.dragData.length; ++i) {
            let itemInfo = this.dragData[i];
            let key = itemInfo.text;
            let item = cc.instantiate(this.box);
            item.parent = this.rect;
            item.width = itemInfo.rect.width;
            item.height = itemInfo.rect.height;
            item.x = itemInfo.rect.x + itemInfo.rect.width / 2;
            item.y = -itemInfo.rect.y - itemInfo.rect.height / 2;
            item.getChildByName("lb").getComponent(cc.Label).string = key;
            item.getChildByName("lb").active = false;
            item.getChildByName("lb").scale = itemInfo.fontScale;
            cc.log("item scale == " + item.scale)
            list[i].scale = 0;
            list[i].active = true;
            cc.tween(list[i]).to(0.3, { scale: 1 }).start();
            let keylist = keyMap.get(key);
            if (!keylist) {
                keylist = [];
            }
            keylist.push(item);
            keyMap.set(key, keylist);
        }

        cc.log(keyMap)

        for (let i = 0; i < this.dragData.length; ++i) {
            list[i].removeAllChildren();
            let itemInfo = this.dragData[i];
            let key = itemInfo.text
            let dragNode = cc.instantiate(this.dragObj);
            dragNode.x = 0;
            dragNode.y = 0;
            dragNode.parent = list[i];
            dragNode.getChildByName("lb").getComponent(cc.Label).string = key;
            dragNode.getComponent(DragObj).setMatchData(key, () => {
                this._rightIndex++;
                if (this._rightIndex == this._totalIndex) {
                    this.toEnd()
                }
            });
            dragNode.getComponent(DragObj).mainCom = this;
            dragNode.getComponent(DragObj).setMatchList(keyMap.get(key))
        }

    }


    async toEnd() {


        asyncPlayDragonBoneAnimation(this.fogeNode, "finish", 1);
        await asyncDelay(0.9)
        this.playLocalAudio("jump")
        await asyncDelay(0.8)
        this.playLocalAudio("jump")
        await asyncDelay(0.8)
        this.playLocalAudio("jump")
        await asyncDelay(0.8)
        this.boyNode.scaleX = 0.5;
        this.fogeNode.active = false;
        this.boyNode.getComponent(Boy).playRun(-1);
        cc.tween(this.boyNode).to(1, { x: 67 }).call(async () => {
            this.playLocalAudio("yeah")
            await this.boyNode.getComponent(Boy).playCheer(1);
            this.boyNode.getComponent(Boy).playtalk(-1);
            this.playAudioByUrl(this.data.end_audio_url, () => {
                this.boyNode.getComponent(Boy).playNormal();
                this.btn_end.active = true;
                this.btn_restart.active = true;

            })

        }).start()


    }
    initListener() {

    }

    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);
            });
        })
    }
}
