
import { _decorator, Node, instantiate, Prefab, UITransform, tween, Vec3 } from 'cc';
import { Consts } from '../Consts';
import { Stage } from '../Data/Sample/Stage';
import { FightConsts } from '../Fight/FightConsts';
import { FightScreenData } from '../Fight/FightScreenData';
import CocosHelper from '../UIFrame/CocosHelper';
import EventManager from '../UIFrame/EventManager';
import SceneMgr from '../UIFrame/SceneMgr';
import { MoveDir } from '../UIFrame/Types';
import { UIScreen } from '../UIFrame/UIScreen';
import { MapItem, MapItemType } from '../Panel/Item/MapItem';
import { FightMap } from '../Panel/Item/FightMap';
import { DataConsts } from '../Data/DataConsts';

const { ccclass, property } = _decorator;

@ccclass('FightScreen')
export class FightScreen extends UIScreen {
    // 地图所在节点
    @property(Node) mapNode: Node = null;

    // 副本数据
    fightScreenData: FightScreenData;

    // 地图节点的宽高
    mapHeight: number;
    mapWidth: number;

    start() {
    }

    onInit() {
        EventManager.addListener(Consts.FIGHT_MAP_MOVE, this.mapMove, this);
        EventManager.addListener(Consts.CLICK_ITEM, this.clickItem, this);
        EventManager.addListener(Consts.CLICK_ITEM_FINISH, this.clickItemFinsh, this);
    }

    onHide() {
        EventManager.removeListener(Consts.FIGHT_MAP_MOVE, this.mapMove, this);
        EventManager.removeListener(Consts.CLICK_ITEM, this.clickItem, this);
        EventManager.removeListener(Consts.CLICK_ITEM_FINISH, this.clickItemFinsh, this);
    }

    onShow(param: any) {
        this.mapWidth = this.mapNode.getComponent(UITransform).width;
        this.mapHeight = this.mapNode.getComponent(UITransform).height;
        this.initMap((param as Stage));
    }

    /**
     * 获得当前显示的地图节点
     */
    getCurrentFightMapNode(): Node {
        return this.mapNode.getChildByName("map_" + this.fightScreenData.getCurrentFightMapX() + "_" + this.fightScreenData.getCurrentFightMapY());
    }


    async initMap(stage: Stage) {
        // 初始化地图数据
        this.fightScreenData = new FightScreenData();
        // console.log("... type=" + stage.type);

        // 先判断当前副本是否是需要保存的
        if (stage.type == DataConsts.MAIN) {
            if (!this.fightScreenData.loadInitData(stage.sid))
                this.fightScreenData.initMapData(stage);
        } else {
            this.fightScreenData.initMapData(stage);
        }
        await this.showCurrentMap();
    }

    /**
     * 显示当前地图
     */
    async showCurrentMap() {
        this.mapNode.removeAllChildren();
        const currentMapData = this.fightScreenData.currentFightMapData;
        let prefab = await CocosHelper.loadResSync(currentMapData.mapPrefabName, Prefab) as Prefab;
        let mn = instantiate(prefab);
        mn.name = "map_" + currentMapData.x + "_" + currentMapData.y;
        mn.getComponent(FightMap).initData(currentMapData);
        mn.parent = this.mapNode;
        this.showAroundMap();
    }

    /**
     * 显示周边的地图
     */
    async showAroundMap() {
        const currentX = this.fightScreenData.getCurrentFightMapX();
        const currentY = this.fightScreenData.getCurrentFightMapY();

        // 4个方向
        // 上
        this.showMap(currentX, currentY - 1);
        // 下
        this.showMap(currentX, currentY + 1);
        // 左
        this.showMap(currentX - 1, currentY);
        // 右
        this.showMap(currentX + 1, currentY);

    }
    /**
     * 显示某地图
     */
    async showMap(x: number, y: number) {
        if (x < 0 || y < 0)
            return;
        if (x >= this.fightScreenData.fightMapDataArraysWidth || y >= this.fightScreenData.fightMapDataArraysHeight)
            return;
        // 判断有没有
        let node = this.mapNode.getChildByName("map_" + x + "_" + y);
        if (!node) {
            const currentMapData = this.fightScreenData.currentFightMapData;
            const currentX = currentMapData.x;
            const currentY = currentMapData.y;
            const currentMapNode = this.mapNode.getChildByName("map_" + currentX + "_" + currentY);

            const currentPosX = currentMapNode.position.x;
            const currentPosY = currentMapNode.position.y;

            let fightMapData = this.fightScreenData.getFightMapData(x, y);

            if (fightMapData) {
                let prefab = await CocosHelper.loadResSync(fightMapData.mapPrefabName, Prefab) as Prefab;
                let mn = instantiate(prefab);
                mn.name = "map_" + x + "_" + y;
                mn.setPosition(currentPosX + ((x - currentX) * this.mapWidth), currentPosY + ((currentY - y) * this.mapHeight));
                mn.getComponent(FightMap).initData(fightMapData);
                mn.parent = this.mapNode;
            }
        }
    }

    /**
     * 切换地图
     * @returns 返回是否可以切换
     */
    switchMap(x: number, y: number): boolean {
        if (this.fightScreenData.switchMap(x, y)) {
            this.showAroundMap();
            const node = this.getCurrentFightMapNode();
            if (node) {
                const fightMap = node.getComponent(FightMap);
                fightMap.refreshSwitchButton();
            }
            return true;
        }
        return false;
    }

    /**
     * 跳转地图
     */
    gotoMap(x: number, y: number) {
        this.fightScreenData.switchMap(x, y);
        this.showCurrentMap();
    }



    /**
     * 移动
     */
    mapMove(dir: MoveDir) {
        const x = this.fightScreenData.currentFightMapData.x;
        const y = this.fightScreenData.currentFightMapData.y;
        switch (dir) {
            case MoveDir.Up:
                if (this.switchMap(x, y - 1))
                    tween(this.mapNode).to(FightConsts.MOVETIME, { position: new Vec3(this.mapNode.position.x, this.mapNode.position.y - this.mapHeight, 0) }, { easing: 'smooth' }).start();
                break;
            case MoveDir.Down:
                if (this.switchMap(x, y + 1))
                    tween(this.mapNode).to(FightConsts.MOVETIME, { position: new Vec3(this.mapNode.position.x, this.mapNode.position.y + this.mapHeight, 0) }, { easing: 'smooth' }).start();
                break;
            case MoveDir.Left:
                if (this.switchMap(x - 1, y))
                    tween(this.mapNode).to(FightConsts.MOVETIME, { position: new Vec3(this.mapNode.position.x + this.mapWidth, this.mapNode.position.y, 0) }, { easing: 'smooth' }).start();
                break;
            case MoveDir.Right:
                if (this.switchMap(x + 1, y))
                    tween(this.mapNode).to(FightConsts.MOVETIME, { position: new Vec3(this.mapNode.position.x - this.mapWidth, this.mapNode.position.y, 0) }, { easing: 'smooth' }).start();
                break;
        }
    }


    /**
     * 点击物件消息
     */
    clickItem(mapItem: MapItem) {
        // 根据物件类型执行
        switch (mapItem.itemType) {
            case MapItemType.DEFAULT:
                break;
            case MapItemType.树木:
                break;
            case MapItemType.草丛:
                break;
            case MapItemType.石头:
                break;
            case MapItemType.矿石:
                break;
            case MapItemType.河流:
                break;
            case MapItemType.宝箱:
                break;
            case MapItemType.迷雾:
                break;
            case MapItemType.草药:
                break;
            case MapItemType.怪物:
                break;
        }
        this.fightScreenData.currentFightMapData.setItemValue(mapItem.num, mapItem.progress);
    }


    /**
     * 完成点击物件消息
     */
    clickItemFinsh(mapItem: MapItem) {
        // console.log("  clickItemFinsh item.type=" + mapItem.itemType + ", " + mapItem.progress);

        const node = this.getCurrentFightMapNode();
        if (!node) {
            console.warn(" cnt find currentMapNode. x=" + this.fightScreenData.getCurrentFightMapX() + ",y=" + this.fightScreenData.getCurrentFightMapY());
            return;
        }
        const fightMap = node.getComponent(FightMap);
        // 根据物件类型执行
        switch (mapItem.itemType) {
            case MapItemType.DEFAULT:
                break;
            case MapItemType.树木:
                break;
            case MapItemType.草丛:
                break;
            case MapItemType.石头:
                break;
            case MapItemType.矿石:
                break;
            case MapItemType.河流:
                break;
            case MapItemType.宝箱:
                break;
            case MapItemType.迷雾:
                break;
            case MapItemType.草药:
                break;
            case MapItemType.怪物:
                fightMap.refreshSwitchButton();
                break;
        }
        this.fightScreenData.currentFightMapData.setItemValue(mapItem.num, mapItem.progress);
    }

    /**
     * 保存战斗数据
     */
    saveFightData() {
        this.fightScreenData.saveData();
    }

    /**
     * 加载
     */
    loadFightData() {
        // this.fightScreenData.loadInitData(1);
    }

    /**
     * 加载
     */
    clearFightData() {
        this.fightScreenData.clearData(1);
    }


    /**
     * 退出战斗
     */
    exitFight() {
        // 判断战斗类型是否需要保存数据

        SceneMgr.back();
    }

    // update (deltaTime: number) {
    //     // [4]
    // }
}