import { _decorator, AudioSource, Component, instantiate, Node, Prefab, Widget } from 'cc';
import { event_group_event_item, event_group_event_item_event_item, event_item, event_item_switch_scene_event, scene_item_data, task_data } from '../../data/data';
import { scene_page } from './scene_page';
import { scene_page_dir } from './scene_page_dir';
import { ClientEvent } from '../clientEvent';
import { config } from '../config';
import { gameManager } from './gameManager';
const { ccclass, property } = _decorator;

class EventTarget{
    event_item: event_item;
    is_finish:boolean;
}

@ccclass('scene_layer')
export class scene_layer extends Component {
    @property(Node) content:Node = null;
    @property(Prefab) scenePagePrefab:Prefab = null;
    @property(Node) scenePageDir:Node = null;
    protected mSceneTask:task_data = null;
    private mTaskEventItemList:Map<string,EventTarget> = new Map;
    protected mScenePages:scene_item_data[] =[]
    private mCurPage:number = 0;
    private mAudioList:Map<string,Node> = new Map;
    private up_id_string = '_up'
    private next_id_string = '_next'
    private is_show_cur_directionBtn:boolean = true; //是否显示当前方向按钮,默认显示
    protected start(): void {
        this.node.addComponent(AudioSource)
    }
    public initSceneTask(data:task_data) {
        this.mSceneTask = data
        this.getTaskSwitchSceneEventList()
    }
    
    public initScene(pages:scene_item_data[],type:number){
        ClientEvent.on(config.EventRun.NOTICE_EVENT,this.beActive.bind(this),this)
        this.mScenePages = pages;
        this.initSceneDir(type)
        this.loadAllPage()
        this.changeHideAllDirectionBtn()
    }

    public unInit(){
        this.content.destroyAllChildren()
        this.content.removeAllChildren()
        this.mSceneTask = null
        this.mTaskEventItemList.clear()
        this.mScenePages = []
        this.mCurPage = 0
        this.mAudioList.clear()
        this.unscheduleAllCallbacks()
        this.is_show_cur_directionBtn = true
        ClientEvent.off(config.EventRun.NOTICE_EVENT,this.beActive.bind(this),this)
    }

    getAudioSource(){
        if(this.node.getComponent(AudioSource)==null){
            this.node.addComponent(AudioSource)
        }
        return this.node.getComponent(AudioSource)
    }
    beActive(widgetId:number,event:event_item){
        if(event.type===config.event_type.play_sound){
            let is_can_play = true;
            if(gameManager.Singleton.getLevelData()){
                if(gameManager.getUserData().isOpenPeiYin){
                    is_can_play = true;
                }else{
                    is_can_play = false;
                }
            }
            if(is_can_play){
                if(event.event_item_play_sound_data!=null){
                    if(event.event_item_play_sound_data.isLoop==undefined){
                        event.event_item_play_sound_data.isLoop = false;
                    }
                    if(event.event_item_play_sound_data.volume==undefined){
                        event.event_item_play_sound_data.volume = 1;
                    }
                    this.addAudioItemAndPlay(event.event_item_play_sound_data.sound_res.url,event.event_item_play_sound_data.volume ,event.event_item_play_sound_data.isLoop)
                }
            }
   
        }else if(event.type===config.event_type.stop_play_loop_sound){
            if(event.event_item_stop_play_loop_sound_data!=null){
                this.deleteAudioItem(event.event_item_stop_play_loop_sound_data.res)
            }
        }else if(event.type===config.event_type.more_scene_is_show_arrow_event) {
            let data = event.event_item_more_scene_is_show_arrow_event_data
            if(data!=null) {
                this.is_show_cur_directionBtn = data.is_show
                if(data.is_show) {
                    this.changeUpNextDirectionBtn()
                } else {
                    this.changeHideAllDirectionBtn()
                }
                gameManager.Singleton.exeNextDelayEvent(event)
            }
        }else if(event.type===config.event_type.more_scene_jump_assigned_page_event){
            let data = event.event_item_more_scene_jump_assigned_page_event_data
            if(data!=null) {
                let page_index = data.page_number-1
                if(page_index>-1 && page_index<this.mScenePages.length) {
                    let interval_time = data.interval_time
                    gameManager.Singleton.onLaunch(()=>{
                        this.changePage(page_index)
                        gameManager.Singleton.exeNextDelayEvent(event)
                    },interval_time)
                }
            }
        } else if(event.type===config.event_type.event_group) {
            let data = event.event_item_event_group_data
            if(data!=null&&data.list.length>0) {
                this.executeEventGroup(event, data)
            }
        }
    }

    addAudioItemAndPlay(res:string, volume:number,isLopp:boolean = false){
        // let content = this.getCurScenePage().node;
        let content = this.content;
        let audio_node = this.mAudioList.get(res)
        if(audio_node==null){
            audio_node = new Node
            audio_node.parent = content;
            audio_node.addComponent(AudioSource)
            this.mAudioList.set(res,audio_node)
        }
        audio_node.getComponent(AudioSource).clip = gameManager.getCacheSoundByName(res);
        audio_node.getComponent(AudioSource).play();
        audio_node.getComponent(AudioSource).volume = volume;
        audio_node.getComponent(AudioSource).loop = isLopp;
    }

    deleteAudioItem(res:string){
        let audio_node = this.mAudioList.get(res)
        if(audio_node){
            audio_node.getComponent(AudioSource).stop()
            audio_node.removeFromParent()
            this.mAudioList.delete(res)
        }
    }
    changePage(page:number){
        this.mCurPage = page;
        this.onChangeUpdatePages()
        this.changeUpNextDirectionBtn()
    }

    changeHideAllDirectionBtn(){
        this.scenePageDir.getComponent(scene_page_dir).hideAllBtn()
    }

    changeUpNextDirectionBtn() {
        if(this.is_show_cur_directionBtn==false) {
            return
        }
        if(this.mScenePages.length>1){
            this.scenePageDir.getComponent(scene_page_dir).showAllBtn()
            if(this.mCurPage<=0){
                this.scenePageDir.getComponent(scene_page_dir).hideUpBtn()
            }
            if(this.mCurPage==this.mScenePages.length-1){
                this.scenePageDir.getComponent(scene_page_dir).hideNextBtn() 
            }
        }
    }

    onChangeUpdatePages(){
        for (let index = 0; index < this.content.children.length; index++) {
            const page = this.content.children[index];
            if(page.getComponent(AudioSource)!=null){

            }else{
                page.active = (this.mCurPage == index)
            }
          
        }
    }

    loadAllPage(){
        this.content.removeAllChildren()
        for (let index = 0; index < this.mScenePages.length; index++) {
            const item_data:scene_item_data = this.mScenePages[index];
            let item:Node = instantiate(this.scenePagePrefab);
            item.parent = this.content;
            item.getComponent(Widget).target = this.content;
            item.getComponent(scene_page).initView(item_data)
        }
        this.changePage(0)
    }

    public getCurScenePage(){
        return this.content.children[this.mCurPage].getComponent(scene_page)
    }

    public isCurScenePageCheckWidgetFinish(widget_id:number):boolean{
        let page:scene_page = this.getCurScenePage()
        return  page.checkFinish(widget_id)
    }

    public isCurScenePageCheckWidgetShow(widget_id:number):boolean{
        let page:scene_page = this.getCurScenePage()
        return  page.checkShow(widget_id)
    }

    onUp(){
        let cur_page = this.mCurPage
        let up_page = this.mCurPage -1;
        if(up_page>=0){
            gameManager.Singleton.onLaunch(()=>{
                this.changePage(up_page)
                this.onClickCurPageDirectionButton(cur_page, true)
            })
        }
    }

    onNext(){
        let cur_page = this.mCurPage
        let next_page = this.mCurPage +1;
        if(next_page<this.mScenePages.length){
            gameManager.Singleton.onLaunch(()=>{
                this.changePage(next_page)
                this.onClickCurPageDirectionButton(cur_page, false)
            })
        }
    }

    onClickCurPageDirectionButton(curPage:number, isUp:boolean) {
        if(this.mSceneTask == null) {
            return
        }
        let event_id = -1
        var key = curPage + ''
        if(isUp) { 
            key = key + this.up_id_string 
        } else {
            key = key + this.next_id_string 
        }
        let eventTarget:EventTarget = this.mTaskEventItemList.get(key)
        if(eventTarget != null && eventTarget.is_finish == false) {
            event_id = eventTarget.event_item.event_id
        }
        // console.log('event_id=',event_id)
        if(event_id != -1) {
            this.checkDelayTimeNextEvent(event_id, eventTarget)
        }
    }

    checkDelayTimeNextEvent(event_id:number, eventTarget:EventTarget) {
        if(eventTarget == null) {
            return
        }
        // 当前数据
        let event_item:event_item = eventTarget.event_item
        let switch_scene_event_data:event_item_switch_scene_event = event_item.event_item_switch_scene_event_data
        // 下一个事件成功的id
        let trigger_event_id = event_item.success.trigger_event_id
        if(trigger_event_id == -1) {
            return
        }
        // 延迟时间
        let call = (()=> {
            gameManager.Singleton.exeSuccessTriggerEvent(trigger_event_id)
        })
        if(switch_scene_event_data.delay_time > 0) {
            this.changeHideAllDirectionBtn()
            let delay_time = switch_scene_event_data.delay_time
            this.scheduleOnce(()=> {
                if(event_item.event_item_switch_scene_event_data.executeOnlyOnce) {
                    eventTarget.is_finish = true
                }
                call()
                this.changeUpNextDirectionBtn()
            },delay_time)
        } else {
            call()
        }

        // 用于下一个是:"延迟时间调用一个事件"
        // let trigger_event_id = eventTarget.event_item.success.trigger_event_id
        // if(trigger_event_id!=-1) {
        //     let _event:event_item = taskServce.getEventById(trigger_event_id)
        //     if(_event!=null && _event.type == config.event_type.delay_exe_event) {
        //         let delay_time = _event.event_item_delay_exe_data.delay_time
        //         // console.log('下一个是延迟事件 延迟时间=',delay_time)
        //         this.scenePageDir.getComponent(scene_page_dir).hideAllBtn()
        //         this.scheduleOnce(()=> {
        //             this.changeUpNextBtn()
        //             if(eventTarget.event_item.event_item_switch_scene_event_data.executeOnlyOnce) {
        //                 eventTarget.is_finish = true
        //             }
        //             this.changeUpNextBtn()
        //         },delay_time)
        //     }
        // }
    }

    getTaskSwitchSceneEventList() {
        if(this.mSceneTask == null) {
            return
        }
        for(let i = 0; i < this.mSceneTask.event_list.length; i++) {
            let element:event_item = this.mSceneTask.event_list[i]
            let element_switch_scene_event_data:event_item_switch_scene_event = element.event_item_switch_scene_event_data
            if(element.type == config.event_type.switch_scene_event && element_switch_scene_event_data != null) {
                if(element_switch_scene_event_data.binding_page_index != -1 && element_switch_scene_event_data.direction != config.switch_scene_page_direction.unknown) {
                    var key = element_switch_scene_event_data.binding_page_index + ''
                    if(element_switch_scene_event_data.direction == config.switch_scene_page_direction.up || element_switch_scene_event_data.direction == config.switch_scene_page_direction.left) {
                        key = key + this.up_id_string
                    } else {
                        key = key + this.next_id_string 
                    }
                    let eventTarget = new EventTarget()
                    eventTarget.event_item = element
                    eventTarget.is_finish = false
                    this.mTaskEventItemList.set(key, eventTarget)
                }
            }
        }
    }

    initSceneDir(type:number){
        if(this.mScenePages.length>1){
            this.scenePageDir.getComponent(scene_page_dir).initView(type,this.onUp.bind(this),this.onNext.bind(this))
        }else{
            this.scenePageDir.getComponent(scene_page_dir).hideAllBtn()
        }
       
    }

    executeEventGroup(event:event_item, data:event_group_event_item) {
        var c_index = 0
        let c_item_data = data.list[c_index]
        let call_back = (()=>{
            c_index++
            if(c_index >= data.list.length) {
                gameManager.Singleton.exeSuccessTriggerEvent(event.success.trigger_event_id)
                return
            }
            c_item_data = data.list[c_index]
            this.runEventGrop(c_item_data, call_back)
        })
        this.runEventGrop(c_item_data,call_back)
    }

    runEventGrop(item_data: event_group_event_item_event_item, callback){
        this.scheduleOnce(()=>{
            gameManager.Singleton.exeEvent(item_data.event_item.event_id)
            callback()
        },item_data.delay_time)
    }
}


