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 ScrollPage = FYGE.ScrollPage;
import Container = FYGE.Container;
import Graphics = FYGE.Graphics;
import Sprite = FYGE.Sprite;
import Texture = FYGE.Texture;
import Tween = FYGE.Tween;
import Ease = FYGE.Ease;
import { changeScene, showPanel, showToast } from "../../../module/ctrls";
import { FreePowerPanel } from "../../panels/FreePowerPanel";
import { sendTbNet, TbNetName } from "../../TaoBaoNet";
import { GDispatcher } from "../../Main";
import { G_EVENT } from "../../common/G_EVENT";
import { RES } from "../../../module/RES";
import TextureCache = FYGE.TextureCache;
import { LoadingScene } from "../LoadingScene";

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;

    private mapAvatar: MapAvatar = null;

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

    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.loginAddPower && !Tools.globalData.isFirstLogin) {
            showPanel(FreePowerPanel);
            Tools.globalData.loginAddPower = false;
        }

        if (this.data && this.data.doSomething && this.data.doSomething == 'toMyPrize') {
            setTimeout(() => {
                sendTbNet(
                    TbNetName.navigateTo,
                    {url: '/pages/myprize/myprize'},
                    () => {
                    },
                    true
                );
            }, 100);
        }

    }

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

    private initGuide() {
        //有bug再说
        // Tools.globalData.isFirstLogin = false;

        const guide = this.addChild(new Container());
        guide.y = -layers.stageOffsetY;
        const g = guide.addChild(new Graphics());
        g.beginFill(0, 0.6);
        g.drawRect(0, 0, 750, 1624);
        g.endFill();


        const mapGuide = guide.addChild(Tools.getSprite('mapGuide.png'));
        mapGuide.anchorTexture.set(0.5, 0.5);
        mapGuide.position.set(375, 650);
        mapGuide.mouseEnable = false;


        const guide_check = guide.addChild(new CheckBtn({check: 1}));
        guide_check.enabled = true;
        guide_check.type = CHECK_TYPE.CUR;
        guide_check.position.set(MapScene.checkArr[1].x, MapScene.checkArr[1].y + 140 * layers.stageOffsetY / 812);
        guide_check.addChild(new MapAvatar());

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

        // 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 + 95, guide_check.y + 45);
        // guide_light.mouseEnable = guide_light.mouseChildren = false;
        //
        // const guide_fox = guide.addChild(Tools.getSprite('guide_fox.png'));
        // guide_fox.position.set(45, guide_check.y - 200);
        // guide_fox.alpha = 0;
        //
        // const guide_tip = guide.addChild(Tools.getSprite('guide_tip.png'));
        // guide_tip.anchorTexture.set(0, 0.3);
        // guide_tip.position.set(guide_fox.x + 215, guide_fox.y - 70);
        // 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 - 345, alpha: 1}, 300, Ease.quadInOut)
        //     .wait(100)
        //     .call(() => {
        //         Tween.get(guide_tip)
        //             .to({scaleX: 1, scaleY: 1}, 300, Ease.quadInOut);
        //     });

    }

    private initMapByData(data = Tools.baseInfo) {
        this.uiLayer.energyBox.count = Tools.propInfo.power;

        const currentLevel = data.currentLevel || 1;

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

        // 当前关卡
        if (currentLevel < 121 && currentLevel > 0) {
            MapScene.checkArr[currentLevel].type = CHECK_TYPE.CUR;
            MapScene.checkArr[currentLevel].enabled = true;
            !this.mapAvatar && (this.mapAvatar = this.addChild(new MapAvatar()));
            this.mapAvatar.parent && this.mapAvatar.parent.removeChild(this.mapAvatar);
            MapScene.checkArr[currentLevel].addChild(this.mapAvatar);
        }

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

        // 闯关记录里有的
        // console.log(data.records);
        if (!Array.isArray(data.records)) data.records = [];
        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(120);

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

        const topData = arr.splice(120 - MapTop.totalCount, 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.scrollPage.maxDistance = maxHeight;
        this.scrollPage.scrollTo(maxHeight, 0);

        this.scrollToCheck(1);
    }

    private scrollToCheck(checkNum: number, time = 0) {
        if (checkNum < 1) {
            checkNum = 1;
        } else if (checkNum > 120) {
            checkNum = 120;
        }
        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();
        this.uiLayer.updateUI();
    }

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

        // Tools.gameOver({
        //     level: 1,
        //     score: 666,
        //     stars: 0,
        //     isVisitSuccess: true,
        //     isPrizeLevel: false,
        //     // tool: {
        //     //     type: 'hammers',
        //     // },
        //     prize: {
        //         image: 'https://img.alicdn.com/imgextra/i1/2275046294/O1CN01xTeKMI1wMhRux48Y6_!!2275046294-2-miniprogram.png',
        //     }
        // });

        // 如果有邀请人就去助力
        if (Tools.globalData.inviteId) {
            sendTbNet(TbNetName.doHelp, {inviteId: Tools.globalData.inviteId},
                (success, res) => {
                    Tools.globalData.inviteId = null;
                    if (success) showToast('助力成功');
                    // if (success) Tools.globalData.inviteId = null;
                }
            );
        }

        // "playScene"
        // "playFrameAni"
        // "playerFont",
        // "fiveVerHorDis"
        // 'festival'
        // 'MagicAni'


        RES.destroyGroup('loadingScene');

        const duration = 1500;
        Tween.get(FYGE)
            .wait(500)
            .call(() => {
                RES.loadGroup('SuccessPanel');
                RES.loadGroup('TaskPanel');
            })
            .wait(duration)
            .call(() => RES.loadGroup('playScene'))
            .wait(duration)
            .call(() => RES.loadGroup('playFrameAni'))
            .wait(duration)
            .call(() => RES.loadGroup('playerFont'))
            .wait(duration)
            .call(() => RES.loadGroup('fiveVerHorDis'))
            .wait(duration)
            .call(() => RES.loadGroup('festival'))
            .wait(duration)
            .call(() => RES.loadGroup('MagicAni'));

    }

    public initEvents() {
        super.initEvents();
        GDispatcher.addEventListener(G_EVENT.ON_SHOW, this.updateScene, this);
    }

    public removeEvents() {
        super.removeEvents();
        GDispatcher.removeEventListener(G_EVENT.ON_SHOW, this.updateScene, this);
    }
}


/**
 * 地图上的头像
 */
export class MapAvatar extends Container {

    private avatarImg: Sprite = null;

    constructor() {
        super();

        this.addChild(Tools.getSprite('map_avatar_bg.png'))
            .anchorTexture.set(0.5, 1);

        this.position.set(54, 32);
        this.mouseChildren = this.mouseEnable = false;

        const mask = this.addChild(new Graphics());
        mask.drawCircle(1, -52, 35);

        this.avatarImg = this.addChild(new Sprite(Texture.fromUrl(
            Tools.globalData.avatar
        )));
        this.avatarImg.width = this.avatarImg.height = 72;
        this.avatarImg.position.set(-36, -87.5);
        this.avatarImg.mask = mask;
    }
}
