import { _decorator, Component, Node } from 'cc';
import JNLayerBase from '../../../../extensions/ngame/assets/ngame/ui/base/JNLayerBase';
import JNScrollView from '../../../../extensions/ngame/assets/ngame/util/components/scrollview/JNScrollView';
import { PetOV, PlayerPetOVSelect } from '../VO/PetOV';
import PlayerPetData from '../../data/PlayerPetData';
import { NodeEventType } from 'cc';
import { PetIconSelectScroll } from '../Consts/Pet/PetIconSelectScroll';
import { PlayerPetOV } from '../../consts/API';
import { app } from '../../App';
import { GUI } from '../UIConfig';
const { ccclass, property } = _decorator;

export interface PetRadioViewArgs{
    isHaveSelect:boolean, //是否必须选择
    resolve?:(value:PlayerPetOV) => {},
}

//宠物单选页面
@ccclass('PetRadioView')
export class PetRadioView extends JNLayerBase {
    
    data:PetRadioViewArgs;

    @property(JNScrollView)
    views:JNScrollView; //宠物列表

    index:number = -1;

    onJNLoad(data?: PetRadioViewArgs): void {

        data = data || {isHaveSelect:false};
        this.isClickMaskeClose = !data.isHaveSelect;
        this.data = data;

        super.onJNLoad();

        this.onUpdateView();
        
    }

    onUpdateView(){
        
        //当前需要升星的宠物并且未上阵 并且排除自己
        let pets = PetOV.PlayerPetOVSelects( PlayerPetData.getIns().getData() );
        this.views.refreshData(pets);
        
        //向子节点添加点击事件
        this.views.addItemEvent(NodeEventType.TOUCH_START,this.onClickItem.bind(this));
        
    }

    //刷新选择
    onUpdateSelect(){

        //刷新
        this.views.getItems<PetIconSelectScroll>().forEach((item) => {
            let data = item.data as PlayerPetOVSelect;
            item.select.isSelect = data.isSelect;
        })

    }

    //点击Item
    onClickItem(index:number){
        this.index = index;
        let pets = this.views.getData<PlayerPetOVSelect>();
        pets.forEach(item => item.isSelect = false);
        pets[index].isSelect = !pets[index].isSelect;
        this.onUpdateSelect();
    }

    //选择宠物
    onClickSelect(){
        let pets = this.views.getData<PlayerPetOVSelect>();
        if(!(pets[this.index])){
            this.data.resolve && this.data.resolve(null)
            if(this.data.isHaveSelect) {
                app.layer.Open(GUI.Tips,{text:"请选择宠物"});
                return;
            }
        }else{
            this.data.resolve && this.data.resolve(pets[this.index]);
        }
        app.layer.CloseNode(this.node);
    }
    
}


