import { buttonOnClick, buttonOnceClick, getSpriteFrimeByUrl,
    asyncGetSpriteFrimeByUrl, playAudioByUrl, asyncLoadDragonBoneAnime,
    asyncDelay, setNetImg } from "../script/util";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {


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

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

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

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

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

    addPreloadImage() {
        // TODO 根据自己的配置预加载图片资源
    }

    addPreloadAudio() {
        // TODO 根据自己的配置预加载音频资源
    }

    addPreloadAnima() {

    }

    showLoading() {
        cc.find(`Canvas/loading`).active = true;
    }
    hideLoading() {
        cc.find(`Canvas/loading`).active = false;
    }

    isOver = false;
    asyncDrawAnswer() {
        return new Promise((resolve, reject) => {
            if (window && window["courseware"]) {
                window["courseware"].getAnswer(null, (ans) => {
                    if (ans) {
                        this.isOver = JSON.parse(ans).isOver;
                        if (this.isOver) {
                            cc.find(`Canvas/btnbg/btn_again`).active = true;
                            cc.find(`Canvas/btnbg/btn_again_dis`).active = false;
                        }
                        const pic = cc.find(`Canvas/border/pic_bg/picture`);
                        getSpriteFrimeByUrl(JSON.parse(ans).pic_url, (frame) => {
                            pic.getComponent(cc.Sprite).spriteFrame = frame;
                            pic.active = true;
                            resolve();
                        });
                    } else {
                        resolve();
                    }
                });
            } else {
                resolve();
            }
        });
    }

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

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

    picture_url = null;
    async initView() {
        this.initBg();
        await this.initTips();
        window["cameraHandler"].takePictureCallback = (err, url) => {
            if (err) {
                console.log(err);
                this.hideLoading();
                return;
            }
            cc.find(`Canvas/border/sure`).active = true;
            cc.find(`Canvas/border/sure_diss`).active = false;

            this.picture_url = url;
            const pic = cc.find(`Canvas/border/pic_bg/picture`);
            getSpriteFrimeByUrl(url, (frame) => {
                pic.getComponent(cc.Sprite).spriteFrame = frame;
                pic.active = true;
                this.playLocalAudio("picload");
                this.hideLoading();
            });
        }

    }

    initBg() {
        const bgNode = cc.find('Canvas/bg');
        bgNode.scale = this._mapScaleMax;
    }

    async initTips() {
        if (this.data.tipSwitch == 0) {
            cc.find("btn_start", this.node).active = false;
            return;
        }
        this.startNode.active = true;

        const data: any = await setNetImg(cc.find("s_group/startbg", this.startNode), this.data.tipBg, { w: 0, h: 0 }, false);
        this.page_view.width = data.w - 240;
        this.page_view.height = data.h - 200;
        this.page_view.x = -(data.w / 2);
        this.data.tipPage.forEach((dt, idx) => {
            let desc = cc.instantiate(this.tip_label);
            desc.getComponent(cc.Label).string = dt.title;
            desc.width = this.page_view.width;
            desc.height = this.page_view.height - 40;
            this.page_view.getComponent(cc.PageView).addPage(desc);
            desc.active = true;
            desc["data"] = dt;
        })
        this.updataTipArrow();


        const btnStart = cc.find("btn_start", this.node);
        await asyncLoadDragonBoneAnime(btnStart, {
            skeJsonData: this.data.imgAni.ske,
            texJsonData: this.data.imgAni.tex,
            texPngData: this.data.imgAni.png
        });

        const animaNode = btnStart['animaNode'];
        const db = animaNode.getComponent(dragonBones.ArmatureDisplay);
        let anis = db.getAnimationNames("armatureName");
        db.playAnimation(anis[0], 0);
    }

    updataTipArrow() {
        let index = this.page_view.getComponent(cc.PageView).getCurrentPageIndex();
        let pages = this.page_view.getComponent(cc.PageView).getPages();
        // this.tip_left.active = pages.length > 0 && index > 0;
        this.tip_right.active = pages.length > 0 && index < pages.length - 1;
        cc.find("s_group/startbg/btn_close", this.startNode).active = index === pages.length - 1;
        let page = pages[index];
        if (page)
            playAudioByUrl(page["data"].audio);
    }

    initListener() {
        const btn = cc.find(`Canvas/border/upload`);
        buttonOnClick(btn, () => {
            this.playLocalAudio("upload");
            this.showLoading();
            window["cameraHandler"].openCamera();
        });

        const sure = cc.find(`Canvas/border/sure`);
        buttonOnClick(sure, async () => {
            // 上报答题结果
            if (window && window["courseware"]) {
                window["courseware"].sendAnswer({isOver: true, pic_url: this.picture_url});
            }
            await this.showFinal();

            const middleLayer = cc.find('middleLayer');
            if (middleLayer) {
                const mc = middleLayer.getComponent('middleLayer');
                // // 切换下一页
                mc.goNextPage();
            } else {
                console.log("==切换下一页==");
            } 
        });
        
        
        const btnStart = cc.find("btn_start", this.node);
        btnStart.on('click', () => {
            if (btnStart['cantClick']) {
              return;
            }
            btnStart['cantClick'] = true;

            this.startNode.active = true;
            let start_ske = btnStart['animaNode'];
            cc.tween(start_ske).to(0.2, { scale: 1 }).start();
            this.updataTipArrow();
        });

        buttonOnClick(cc.find("s_group/startbg/btn_close", this.startNode), () => {
            cc.audioEngine.stopAll();
            const btnStart = cc.find("btn_start", this.node);
            let start_ske = btnStart['animaNode'];
            cc.tween(start_ske).to(0.2, { scale: 0.3 }).call(() => {
                cc.find("btn_start", this.node)['cantClick'] = false;
            }).start();
            this.page_view.getComponent(cc.PageView).setCurrentPageIndex(0);
            this.startNode.active = false;
        }, 0.6);

        const tipRight = cc.find("s_group/startbg/tip_right", this.startNode);
        buttonOnClick(tipRight, () => {
            tipRight.active = false;
            let index = this.page_view.getComponent(cc.PageView).getCurrentPageIndex();
            this.page_view.getComponent(cc.PageView).scrollToPage(index + 1, 0.3);
            this.updataTipArrow();
        }, 0.6);
    }

    async showFinal() {
        let final = cc.find("final", this.node);
        let f_group = cc.find("f_group", final);
        f_group.scale = 1;
        f_group.setPosition(0, -265);
        f_group.active = true;

        await asyncLoadDragonBoneAnime(f_group, {
            skeJsonData: this.data.endImgAni.ske,
            texJsonData: this.data.endImgAni.tex,
            texPngData: this.data.endImgAni.png
        });
        const animaNode = f_group['animaNode'];
        const db = animaNode.getComponent(dragonBones.ArmatureDisplay);
        let anis = db.getAnimationNames("armatureName");
        db.playAnimation(anis[0], 0);

        this.playLocalAudio("success");

        final.active = true;
        let desc = cc.find("desc", f_group);
        let final_title = cc.find("final_title", f_group);

        let head = cc.find("top/player/mask", this.node);
        let worldPoint = head.convertToWorldSpaceAR(cc.v2(0, 0));
        let pos = final.convertToNodeSpaceAR(worldPoint);
        desc.getComponent(cc.Label).string = this.data.endImgTitle;
        await asyncDelay(2);
        desc.active = true;
        final_title.active = true;

        await asyncDelay(1);
        let sc = cc.scaleTo(0.2, 0.2);
        var actionTo = cc.jumpTo(1, cc.v2(pos.x, pos.y), 300, 1);
        let call = cc.callFunc(() => {
            final.active = false;
        })
        f_group.runAction(cc.sequence(sc, actionTo, call));
    }

    playLocalAudio(audioName) {
        cc.audioEngine.stopAll();
        const audio = cc.find(`Canvas/res/audio/${audioName}`).getComponent(cc.AudioSource);
        cc.audioEngine.playEffect(audio.clip, false);
    }

    onLeave(cb) {
        if (!this.isOver) {
            const tips = cc.find("tips", this.node);
            cc.find(`continue`, tips).active = true;
            cc.find(`leave`, tips).active = true;
            cc.find(`btn_bl`, tips).active = false;
            cc.find(`btn_zcdt`, tips).active = false;
            tips.active = true;

            cc.find(`desc`, tips).getComponent(cc.Label).string = "确定放弃本次答题么？";

            buttonOnceClick(cc.find(`continue`, tips), () => {
                tips.active = false;
            });

            buttonOnceClick(cc.find(`leave`, tips), () => {
                tips.active = false;
                cb();
            });
        } else {
            cb();
        }
    }
    goBack() {
        this.onLeave(() => {
            const middleLayer = cc.find('middleLayer');
            if (middleLayer) {
                const mc = middleLayer.getComponent('middleLayer');
                // 切换上一页
                mc.goPrePage();
            } else {
                console.log("==切换上一页==");
            } 
        });
    }
    goNext() {
        this.onLeave(() => {
            const middleLayer = cc.find('middleLayer');
            if (middleLayer) {
                const mc = middleLayer.getComponent('middleLayer');
                // // 切换下一页
                mc.goNextPage();
            } else {
                console.log("==切换下一页==");
            } 
        });
    }
    goHome() {
        this.onLeave(() => {
            const middleLayer = cc.find('middleLayer');
            if (middleLayer) {
                const mc = middleLayer.getComponent('middleLayer');
                // 回首页
                mc.goTarIndexPage(this.data.jumpIdx || 0);
            } else {
                console.log("==回首页==", this.data.jumpIdx);
            } 
        });
    }

    goRestart() {
        const tips = cc.find("tips", this.node);
        cc.find(`continue`, tips).active = false;
        cc.find(`leave`, tips).active = false;
        cc.find(`btn_bl`, tips).active = true;
        cc.find(`btn_zcdt`, tips).active = true;
        tips.active = true;

        cc.find(`desc`, tips).getComponent(cc.Label).string = "确定重新开始么？";

        buttonOnceClick(cc.find(`btn_bl`, tips), () => {
            tips.active = false;
        });

        buttonOnceClick(cc.find(`btn_zcdt`, tips), () => {
            tips.active = false;
            const pic = cc.find(`Canvas/border/pic_bg/picture`);
            pic.getComponent(cc.Sprite).spriteFrame = null;
            pic.active = false;
        });
    }

}
