import { _decorator, EventTouch, Node, Label,Animation, Vec3, EditBox} from 'cc';
import List from '../third/List';
import { Utils } from '../utils/Utils';
import MsgHints from '../utils/MsgHints';
import { userIns } from '../data/UserData';
import { BaseExp } from '../core/base/BaseExp';
import { autoBind } from '../extend/AutoBind';
import { Constants } from '../data/Constants';
import { uiMgr } from '../core/manager/UIManager';
import { TaskItem } from '../items/item/TaskItem';
import { stateMgr } from '../core/manager/StateManager';
import { Game } from '../game/Game';
import i18n from '../core/i18n/runtime-scripts/LanguageData';
const { ccclass, property } = _decorator;

@ccclass('Main')
export class Main extends BaseExp {
    @autoBind(EditBox)
    public editBox: EditBox = null!;
    @autoBind({ type: Label, tooltip: "金币文本" })
    public gold_lable: Label;
    @autoBind({ type: Label, tooltip: "钻石文本" })
    public diamond_lable: Label;
    @autoBind({ type: Label, tooltip: "任务描述" })
    public task_des_lable: Label;
    @autoBind({ type: Label, tooltip: "关卡等级" })
    public level_lable: Label;
    @autoBind({ type: List, tooltip: "任务数据" })
    public task_scrollView: List;
    @property({ type: Animation, tooltip: "进入游戏动画" })
    public enterAnim: Animation;
    @property({ type: [Node], tooltip: "动画位置节点数组" })
    public animPosArr: Array<Node> = [];

    //所有主要页面
    private sceneNames: Array<string> = [Constants.mainUIs.main];
    //tabBars数组下标
    public _tabBarIndex: number = -1;
    public set tabBarIndex(index: number) {
        this.cutTabBarIndex(null,index);
    }
    public get tabBarIndex(){
        return this._tabBarIndex;
    }
    //保存点击的页面
    private preIndexs: Array<number> = [0];
    //任务数据
    private taskDatas: Array<any> = [];
    //属性存储初始位置
    private originalPositions: Vec3[] = [];
    //是否重新启动加载地图
    private isLoad: boolean = false;

    start() {
        this.hasAnim = false;
        this.closeOnBlank = false;
        //存储初始位置到类属性
        this.originalPositions = this.animPosArr.map(e => e.position.clone());
        uiMgr.panels.set(Constants.mainUIs.main, this.node);
        //注册动态变化值
        stateMgr.registerUI(Constants.gold, this.gold_lable);
        stateMgr.registerUI(Constants.diamond, this.diamond_lable);
        //加载数据
        this.loadData();
        //注册事件
        this.node.on(Node.EventType.TOUCH_START, this.playBtn.bind(this), this);
        if(!Constants.isDebug){
           this.editBox.node.active = false;
        }
    }

    /**
     * 加载数据
     */
    public loadData() {
        const data: any = userIns.getCurLevelData();
        if(!data)return;
        //设置任务描述关卡任务:%{value}
        this.task_des_lable.string = i18n.isZh ? data.task : data.task_lang;
        this.level_lable.string = i18n("main.关卡任务:%{value}",{value: data.id});
        this.taskDatas = []
        //拆分并处理每个敌人配置
        data.dispose.split('|').forEach((item: string) => {
            const [enemyId, count] = item.split('_').map(Number);
            const enemyData = Utils.clone(userIns.enemyTable).find((e: any) => e.id === enemyId);
            enemyData.count = count;
            this.taskDatas.push(enemyData);
        });
        if(this.taskDatas.length <= 0)return;
        this.task_scrollView.numItems = this.taskDatas.length;
    }
    
    /**
     * 任务数据
     * @param item item节点
     * @param idx 数据下标
     */
    public setTaskItemData(item: Node, idx: number) {
        const task: any = this.taskDatas[idx];
        item.getComponent(TaskItem).init(task);
    }

    /**
     * 开始游戏
     */
    public playBtn(){
        if(this.isLoad){
           Game.I.loadMap();
        }
        Game.I.player.restart();
        if(Constants.isDebug && !Utils.isNull(this.editBox.string)){
           userIns.data.level = parseInt(this.editBox.string);
        }
        this.isLoad = true;
        this.enterAnim.play();
        this.scheduleOnce(() => {
            uiMgr.hide(Constants.mainUIs.main,()=>{
                uiMgr.show(Constants.popUIs.gunfightShootUI);
            });
            //加载敌人
            Game.I.buildEnemys.loadLevelEnemys();
        },0.4)
    }
    
    /**
     * 点击事件
     * @param event 事件
     * @param customEventData 数据
     */
    public onBtnClicked(event: EventTouch, customEventData: any) {
        super.onBtnClicked(event,customEventData);
        let btnName = event.target.name;
        if (btnName === 'set_btn') { // 设置页面
            uiMgr.show(Constants.popUIs.settingUI);
        }else if (btnName === 'shop_btn') {//商店
            uiMgr.show(Constants.popUIs.storeUI);
        }else if (btnName === 'arsenal_btn') {//武器库
            uiMgr.show(Constants.popUIs.arsenalUI);
        }else if(btnName === 'boomerang_btn'){//扔飞镖
            uiMgr.show(Constants.popUIs.tossBoomerangUI);
        }else if(btnName === 'ads_free_btn'){//免广告按钮
            MsgHints.show('免广告按钮');
        }else if(btnName === 'bulls_eye_btn'){//准心开始按钮
            this.playBtn();
        }
    }

    /**
     * 切换游戏主页面
     * @param idx 
     */
     public cutTabBarIndex(event: EventTouch,param: any){
        let index: number = parseInt(param);
        this._tabBarIndex = index;
        this.preIndexs.push(index);
        //设置层级
        let path: string = this.sceneNames[index];
        if(path == Constants.mainUIs.main){
           this.animPosArr.forEach((e, index) => e.position = this.originalPositions[index]);
        }
        //加载页面
        uiMgr.show(path);
        if(this.preIndexs.length > 2){
           this.preIndexs.shift()
        }
    }
}

