import { Scene } from "../../../module/views/Scene";
import MapBottom from "./MapBottom";
import MapTop from "./MapTop";
import MapUI from "./MapUI";
import MapMid from "./MapMid";
import CheckBtn, { CHECK_TYPE } from "./CheckBtn";
import { layers } from "../../../module/views/layers";
import { Tools } from "../../Tools";
import { showPanel } from "../../../module/ctrls";
import { FreePowerPanel } from "../../panels/FreePowerPanel";
import { GDispatcher } from "../../Main";
import { HelpPanel } from "../../panels/HelpPanel";
import ScrollPage = FYGE.ScrollPage;
import Container = FYGE.Container;
import Graphics = FYGE.Graphics;
import Tween = FYGE.Tween;
import Ease = FYGE.Ease;

export class MapScene extends Scene {
    private mapContainer: Container = null;
    private scrollPage: ScrollPage = null;

    public static checkArr: CheckBtn[] = [];   // 关卡按钮容器

    public destroy() {
        super.destroy();
        // MapScene.checkArr = [];
    }

    private uiLayer: MapUI = null;

    public get groupNames(): string[] {
        return [
            'map',
            'mapCheckPrizeEffect'
        ];
    }

    protected initUi() {
        super.initUi();
        this.scrollPage = this.addChild(new ScrollPage(
            750, layers.stageHeight,
            888, true, true
        ));
        this.mapContainer = this.scrollPage.view.addChild(new Container());
        // this.uiLayer = this.addChild(new MapUI());//待测试，在下面updateMapCheck里再初始化
        this.initMap();
        this.updateMapCheck();

        if (!Tools.globalData.isNewUser && Tools.globalData.loginAddPower > 0) {    // 不是新用户且加体力
            showPanel(FreePowerPanel, {
                loginAddPower: Tools.globalData.loginAddPower
            });
        }
        Tools.globalData.loginAddPower = 0;


        if (Tools.globalData.inviteId) {    // 有邀请码，唤起弹窗
            showPanel(HelpPanel);
        }

    }

    private updateMapCheck() {
        if (this.data && this.data.from == 'loading') {
            this.uiLayer = this.addChild(new MapUI());
            this.initMapByData(Tools.gameData);
            this.uiLayer.updateUI();
            if (Tools.globalData.isNewUser) {
                this.initGuide();
            }
        } else {
            Tools.getGameInfo().then((success) => {
                if (success) {//不考虑失败的情况
                    this.uiLayer = this.addChild(new MapUI());
                    this.initMapByData(Tools.gameData);
                    this.uiLayer.updateUI();
                }
            });
        }
    }

    private initGuide() {
        setTimeout(() => this.scrollToCheck(3));

        const guide = this.addChild(new Container());
        const g = guide.addChild(new Graphics());
        g.beginFill(0, 0.6);
        g.drawRect(0, 0, layers.stageWidth, layers.stageHeight);
        g.endFill();
        const guide_check = guide.addChild(new CheckBtn({ check: 1 }));
        guide_check.enabled = true;
        guide_check.type = CHECK_TYPE.CUR;

        const checkY = MapScene.checkArr[3].y + 40 - layers.stageOffsetY;
        guide_check.position.set(MapScene.checkArr[1].x, checkY);

        const guide_light = guide.addChild(Tools.getSprite('guide_light.png'));
        guide_light.anchorTexture.set(0.5, 0.5);
        guide_light.position.set(guide_check.x + 130, guide_check.y + 82);
        guide_light.mouseEnable = guide_light.mouseChildren = false;

        const guide_hand = guide.addChild(Tools.getSprite('guide_hand.png'));
        guide_hand.position.set(guide_check.x + 110, guide_check.y + 60);
        guide_hand.mouseEnable = guide_hand.mouseChildren = false;

        const guide_fox = guide.addChild(Tools.getSprite('guide_fox.png'));
        guide_fox.position.set(45, guide_check.y + 415);
        guide_fox.alpha = 0;

        const guide_tip = guide.addChild(Tools.getSprite('guide_tip.png'));
        guide_tip.anchorTexture.set(0.2, 1);
        guide_tip.position.set(guide_fox.x + 200, guide_fox.y + 20);
        guide_tip.scale.set(0, 0);

        guide.alpha = 0;

        Tween.get(guide)
            .to({ alpha: 1 }, 600, Ease.quadInOut);

        Tween.get(guide_fox)
            .wait(300)
            .to({ y: guide_check.y + 415, alpha: 1 }, 300, Ease.quadInOut)
            .wait(100)
            .call(() => {
                Tween.get(guide_tip)
                    .to({ scaleX: 1, scaleY: 1 }, 300, Ease.quadInOut);
            });
    }

    private initMapByData(data) {

        const currentLevel = data.currentLevel;

        // 已经通关的
        for (let i = 1; i < currentLevel; i++) {
            MapScene.checkArr[i].type = CHECK_TYPE.COM;
            MapScene.checkArr[i].enabled = true;
        }

        // 当前关卡
        if (currentLevel < 100 && currentLevel > 0) {
            MapScene.checkArr[currentLevel].type = CHECK_TYPE.CUR;
            MapScene.checkArr[currentLevel].enabled = true;
        }

        // 未通关的
        for (let i = currentLevel + 1; i < 100; i++) {
            MapScene.checkArr[i].type = CHECK_TYPE.COM;
            MapScene.checkArr[i].enabled = false;
        }

        // 闯关记录里有的
        data.records.forEach((v) => {
            MapScene.checkArr[v.level].data = v;
        });

        if (this.data && this.data.level) {
            this.scrollToCheck(this.data.level);
            MapScene.checkArr[this.data.level].clickStart();
        } else {
            this.scrollToCheck(currentLevel);
        }
    }

    public initMap() {
        const arr = new Array(Tools.maxLevel);

        for (let i = 0; i < Tools.maxLevel; i++) {
            arr[i] = {
                check: i + 1
            };
        }
        arr.reverse();

        const topData = arr.splice(98, MapTop.totalCount);  // 得到顶部的数据
        const bottomData = arr.splice(0, MapBottom.totalCount); // 得到尾部的数据
        const midData = arr; // 剩下的是中间的数据

        let maxHeight = MapTop.HEIGHT;
        this.mapContainer.addChild(new MapTop(topData));

        for (let i = midData.length / MapMid.totalCount - 1; i >= 0; i--) {
            const data = midData.splice(i * MapMid.totalCount, MapMid.totalCount);
            const nMid = new MapMid(data);
            this.mapContainer.addChild(nMid);
            nMid.y = maxHeight;
            maxHeight += MapMid.HEIGHT;
        }

        const bottom = new MapBottom(bottomData);
        this.mapContainer.addChild(bottom);
        bottom.y = maxHeight;
        maxHeight += MapBottom.HEIGHT;

        // this.mapContainer.addChild(new MapTop(topData));    // 最后加，因为有个层级问题

        this.scrollPage.maxDistance = maxHeight;
    }

    private scrollToCheck(checkNum: number, time = 0) {
        if (checkNum < 1) {
            checkNum = 1;
        } else if (checkNum > Tools.maxLevel) {
            checkNum = Tools.maxLevel;
        }
        const check = MapScene.checkArr[checkNum];
        const checkY = check.y + check.parent.y - layers.stageHeight / 2 + 50;
        this.scrollPage.scrollTo(checkY, time);
    }

    public async updateScene() {
        super.updateScene();
        await Tools.updatePower();
        this.uiLayer.updateUI();
    }

    public start(data?: any) {
        super.start(data);

        // Tools.gameOver({
        //     "isVisitSuccess": true,
        //     "prize": undefined,
        //     "level": 99,
        //     "score": 58940,
        //     "stars": 3
        // });

    }

    public initEvents() {
        super.initEvents();
        GDispatcher.addEventListener('UpdateScene', this.updateScene, this);
    }

    public removeEvents() {
        super.removeEvents();
        GDispatcher.removeEventListener('UpdateScene', this.updateScene, this);
    }
}

