import { _decorator, Component, instantiate, Node, Prefab } from 'cc';
import { event_group_event_item, event_group_event_item_event_item, event_item } from '../../../data/data';
import { edit_event_group_item } from './edit_event_group_item';
import { tools } from '../../tools';
import { Attributes } from '../Attributes';
const { ccclass, property } = _decorator;

@ccclass('event_group')
export class event_group extends Component {
    @property(Node) btn_add_event:Node = null;
    @property(Node) content:Node = null;
    @property(Prefab) item_prefab:Prefab = null;
    private m_event_item_data:event_item = null;
    private m_data:event_group_event_item = null;
    start() {
        this.btn_add_event.on(Node.EventType.TOUCH_END, ()=>{
            let list = Attributes.Singleton.getEventList()
            tools.show_select_evele_list(list,(data:event_item)=>{
                if(data==null) {
                    return tools.showToast('选择事件是空的,请检查!')
                }
                if(this.m_event_item_data.event_id == data.event_id) {
                    return tools.showToast('事件组中不能添加自己!!!')
                }
                let item = new event_group_event_item_event_item
                item.event_item = data
                item.delay_time = 0
                this.m_data.list.push(item)
                this.updateContent()
            })
        })
    }

    initView(event_item_data:event_item, data:event_group_event_item) {
        this.m_event_item_data = event_item_data
        this.m_data = data
        this.updateContent()
    }

    updateContent() {
        this.content.removeAllChildren()
        for(let index = 0; index<this.m_data.list.length; index++) {
            const element = this.m_data.list[index]
            let item = instantiate(this.item_prefab)
            item.parent = this.content
            item.getComponent(edit_event_group_item).initView(index, this.m_data.list.length, element, ()=>{
                tools.show_dialog("是否确定删除",()=>{
                    this.m_data.list.splice(index,1)
                    this.updateContent()
                })
            }, this.onItemUpDownOperation.bind(this))
        }
    }

    onItemUpDownOperation(item:edit_event_group_item, isUp:boolean) {
        let c_index = item.getIndex()
        let c_data = this.m_data.list[c_index]
        let move_index=-1;
        if(isUp) {
            move_index = c_index - 1
        } else {
            move_index = c_index + 1
        }
        if(move_index == -1) {return}
        let move_data = this.m_data.list[move_index]
        this.m_data.list[c_index] = move_data
        this.m_data.list[move_index] = c_data
        this.updateContent()
    }
}

