import { _decorator, Component, Node } from 'cc';
import JNScrollView from '../../../../../extensions/ngame/assets/ngame/util/components/scrollview/JNScrollView';
import { app } from '../../../App';
import GOnHookManager, { GOnHookManagerEvent } from '../../../manager/battle/mode/GOnHookManager';
import { GOnHookPet } from '../../../../../extensions/ngame/assets/ngame/message/proto';
import { MainSreepsIcon } from './MainSreepsIcon';
import { NodeEventType } from 'cc';
import { GUI } from '../../UIConfig';
const { ccclass, property } = _decorator;

@ccclass('MainSreepsList')
export class MainSreepsList extends Component {
    
    //野怪列表
    @property(JNScrollView)
    views:JNScrollView;

    //默认选择
    index:number = 0;

    onLoad(){

        //监听 野怪死亡
        app.event.on(GOnHookManagerEvent.ADD_KILL_SREEP,this.onAddSreep,this);
        //监听 野怪删除
        app.event.on(GOnHookManagerEvent.DEL_KILL_SREEP,this.onDelSreep,this);
        //监听 野怪数据重置
        app.event.on(GOnHookManagerEvent.RESET_DATA,this.onResetData,this);

        //添加子节点事件
        this.views.addItemEvent(NodeEventType.TOUCH_END,this.onClickItem.bind(this));

    }

    protected onDestroy(): void {
        
        //取消监听
        app.event.off(GOnHookManagerEvent.ADD_KILL_SREEP,this.onAddSreep,this);
        app.event.off(GOnHookManagerEvent.DEL_KILL_SREEP,this.onDelSreep,this);
        app.event.off(GOnHookManagerEvent.RESET_DATA,this.onResetData,this);
    }
    
    //重置数据
    onResetData(){
        this.views.refreshData([]);
    }

    //添加野怪
    onAddSreep(sreep:GOnHookPet){
        this.views.addData(sreep);
        this.onUpdateView();
    }

    //删除野怪
    onDelSreep(sreep:GOnHookPet){
        this.views.delData(sreep);
        this.onUpdateView();
    }

    //刷新
    onUpdateView(){

        let items = this.views.getItems<MainSreepsIcon>();

        if(items.length <= 0) return;

        //取消选中
        items.forEach(item => item.icon.isSelect = false)

        //选中index
        if(items[this.index]) items[this.index].icon.isSelect = true;

    }

    //点击子节点
    onClickItem(index:number){

        this.index = index;
        this.onUpdateView();

    }

    //捕捉野怪
    async onClickCatch(){

        //获取选中的野怪
        let item = this.views.getItems<MainSreepsIcon>()[this.index];

        if(!item){
            app.layer.Open(GUI.Tips,{text:"请选择需要捕捉的宠物"});
            return;
        }

        await GOnHookManager.getIns().onCatchCreeps(item.data)

    }

    //野怪出售
    async onClickSell(){

        //获取选中的野怪
        let item = this.views.getItems<MainSreepsIcon>()[this.index];

        if(!item){
            app.layer.Open(GUI.Tips,{text:"请选择需要出售的宠物"});
            return;
        }

        await GOnHookManager.getIns().onSellCreeps(item.data)

    }
    

}


