import { _decorator, assetManager, Component, ImageAsset, instantiate, Label, Node, Prefab, SpriteFrame, Texture2D } from 'cc';
import { select_res_type } from './select_res_type';
import { control } from './edit/control';
import { select_res_list_item } from './select_res_list_item';
import { bag_item_data } from '../data/data';
const { ccclass, property } = _decorator;

@ccclass('select_res_list')
export class select_res_list extends Component {
    @property(Node) select_res_type:Node = null;
    @property(Node) content:Node = null;
    @property(Prefab) item_prefab:Prefab = null;
    @property(Node) btn_sure:Node = null;
    @property(Node) btn_close:Node = null;
    @property(Node) lab_title:Node = null;
    private m_call_back = null;
    private m_cur_select_item:select_res_list_item = null;
    public initView(call){
        this.m_call_back = call;
        this.select_res_type.getComponent(select_res_type).initView(this.start_show_view.bind(this))
        this.btn_sure.on(Node.EventType.TOUCH_END,()=>{
            if(this.m_call_back!=null){
                this.m_call_back(this.m_cur_select_item.getData())
            }
            this.close()
        })
        this.btn_close.on(Node.EventType.TOUCH_END,()=>{
            this.close()
        })
    }
    close(){
        this.node.removeFromParent()
    }

    onItemClick(item:select_res_list_item){
        this.unSelectAll()
        this.m_cur_select_item = item
        this.lab_title.getComponent(Label).string =  this.m_cur_select_item.getData().name
        this.m_cur_select_item.selectStatus()
    }

    unSelectAll(){
        for (let index = 0; index < this.content.children.length; index++) {
            const element = this.content.children[index];
            element.getComponent(select_res_list_item).unSelectStatus()
        }
    }

    start_show_view(type:number){
        this.select_res_type.active = false;
        let res_list = control.Singleton.getResDataByType(type)
        for (let index = 0; index < res_list.length; index++) {
            const element = res_list[index];
            let item = instantiate(this.item_prefab)
            item.parent = this.content;
            item.getComponent(select_res_list_item).initView(element,this.onItemClick.bind(this))
            if(index ===0){
                this.m_cur_select_item = item.getComponent(select_res_list_item);
                this.m_cur_select_item.selectStatus()
                this.lab_title.getComponent(Label).string =  this.m_cur_select_item.getData().name
            }else{
                item.getComponent(select_res_list_item).unSelectStatus()
            }
        }
    }


}


