import { _decorator, AudioClip, AudioSource, Component, Node, Size, Sprite, SpriteFrame, sys, UITransform, Vec3 } from 'cc';
import { game_run } from './game_run';
import { attributes_data, event_item, LevelItemData, other_widget_finish_listen_item, scene_item_data, sysMessage, task_data, ui_att_item, UserData, widget_item_data } from '../../data/data';
import { config } from '../config';
import { sceneManager } from './sceneManager';
import { control } from '../edit/control';
import { http } from '../http';
import { tools } from '../tools';
import { main } from '../main';
import { taskServce } from './TaskSchedule/taskServce';
import { ClientEvent } from '../clientEvent';
import { sysSound } from './sysSound';
const { ccclass, property } = _decorator;

@ccclass('gameManager')
export class gameManager extends Component {
    private mGameRun:game_run = null;
    private mGameData:scene_item_data[] = [];
    private mCurSceneIndex:number =0; //当前第几个场景
    public static Singleton:gameManager = null;
    private static g_userData:UserData;
    public static res_map:Map<string,SpriteFrame> = new Map()
    public static mp3_cache:Map<string,AudioClip> = new Map()
    private mLevelData:LevelItemData = null;
    private static sys_data:sysMessage = null;
    @property(sceneManager) mSceneManager:sceneManager = null;
    @property(sysSound) mSysSound:sysSound = null;
    protected start(): void {
        gameManager.Singleton  = this;
    }

    public static loadSceneRes(level_id:number,scene_num:number,cb){
        let count = 0;
        let num = 0;
        let scene_count = 1;
        // console.log("scene_num",scene_num)
        let call = ()=>{
            count++;
            // console.log("scene_num",scene_num,scene_count,count,num)
            if(scene_count>=scene_num){
                if(count>=num){
                    // console.log("gameManager.res_map",gameManager.res_map)
                    cb()
                }
            }
        }

        for (let i = 0; i <= scene_num; i++) {
            let url = http.get_level_resource(level_id,i)
            http.run_get(url,(err,data)=>{
                if(!err){
                    let _data = JSON.parse(data)
                    scene_count++;
                    num += _data.content.length;
                    // console.log("run_get:",_data.content.length)
                    for (let index = 0; index < _data.content.length; index++) {
                        const url:string = _data.content[index];
                        console.log('url=',url)
                        let hz = url.substring(url.length-3,url.length);
        
                        if(hz==="png"||hz==="jpg"){
                            // if(gameManager.res_map.get(url)!=null){
                            //     call()
                            // }else{
                  
                            // }
                            tools.loadSceneImg(url,(d)=>{
                                gameManager.res_map.set(d.url,d.sf)
                                call()
                            })
                
                        }
                        if(hz==="mp3"){
                            // if(gameManager.mp3_cache.get(url)!=null){
                            //     call()
                            // }else{
                        
                            // }
                            tools.loadSceneMp3(url,(d)=>{
                                gameManager.mp3_cache.set(d.url,d.clip)
                                call()
                            })
                        }
                        
              
                    }
                }else{
                    tools.showToast(`获取关卡错误${err}`)
                }
            })
        }
    }

    public setLevelData(data:LevelItemData){
        this.mLevelData = data;
    }

    public getLevelData(){
        return this.mLevelData;
    }

    public  static setSysData(data:sysMessage){
        gameManager.sys_data = data;
    }

    public static getSysData(){
        return gameManager.sys_data;
    }

    public static loadSceneMp3(){

    }

    public static getUserData():UserData{
        let str = sys.localStorage.getItem(config.USER_DATA)
        if(str==undefined||str==""||str==null){
            return null;
        }
        let user:UserData = JSON.parse(str)
        return user;
    }

    public static getStaticUserData(){
        return  gameManager.g_userData
    }

    public static setUserData(user:UserData){
        gameManager.g_userData = user;
        gameManager.saveUserData()
    }

    public static saveUserData(){
        if(gameManager.g_userData!=null){
            sys.localStorage.setItem(config.USER_DATA, JSON.stringify(gameManager.g_userData));
        }
    }

    public reLife(){
        gameManager.Singleton.startLevelGame()
    }

    public reStartGame(){
        this.mCurSceneIndex = 0;
        gameManager.Singleton.startLevelGame()
    }

    public levleIsUnLock(levle_id:number){
        let isunlock = false;
        for (let index = 0; index < gameManager.getStaticUserData().unlock_levels.length; index++) {
            const id = gameManager.getStaticUserData().unlock_levels[index];
            if(id==levle_id){
                isunlock = true;
                break;
            }
        }
        return isunlock
    }

    public unLockLevel(levle_id:number){
        let is_have = false;
        for (let index = 0; index < gameManager.getStaticUserData().unlock_levels.length; index++) {
            const id = gameManager.getStaticUserData().unlock_levels[index];
            if(id==levle_id){
                is_have = true;
                break;
            }
        }
        if(!is_have){
            gameManager.getStaticUserData().unlock_levels.push(levle_id)
            gameManager.saveUserData()
            gameManager.Singleton.sync_data()
        }
    }

    public sync_data(){
        let url = http.sync_data()
        let unlock_levels = gameManager.getStaticUserData().unlock_levels;
        http.run_post(url,{"unlock_levels":JSON.stringify(unlock_levels)},(err,data)=>{
            if(!err){
               
            }
        })
    }

    public nextScene(){
        this.onLaunch(()=>{
            this.mCurSceneIndex++;
            let not_scene = false;
            if(this.mCurSceneIndex>=this.mGameData.length){
                not_scene = true;
            }
            if(!not_scene){
                this.mGameRun.unInit()
                this.startLevelGame()
            }else{
                // tools.showToast("没有场景了！")
            }
        })
    }
    public gameOver(){
        ClientEvent.dispatchEvent(config.EventRun.ON_WIN)
    }

    public backGameList(){
        if(this.getLevelData()!=null){
            this.unscheduleAllCallbacks()
            this.mGameRun.backGameList()
        }
    }

    public initEvent(){
        ClientEvent.offAll(config.EventRun.NOTICE_EVENT)
        ClientEvent.offAll(config.EventRun.WIDGET_FINISH)
        ClientEvent.offAll(config.EventRun.WIDGET_FAIL)
        ClientEvent.offAll(config.EventRun.ON_WIDGET_FINISH_COLLECT_EVENT)
        ClientEvent.offAll(config.EventRun.WIDGET_HIDE)
        ClientEvent.offAll(config.EventRun.SHOW_ZHAO_BU_TONG_FINISH_STATUS)
        ClientEvent.offAll(config.EventRun.ON_ZHAO_BU_TONG_ALL_FINISH)
        ClientEvent.offAll(config.EventRun.TOP_VIEW_CLOSE)
        ClientEvent.offAll(config.EventRun.TOP_VIEW_FINISH)
        ClientEvent.offAll(config.EventRun.TOP_VIEW_FAIL)
        ClientEvent.offAll(config.EventRun.ON_COUNT_DOWN_FAIL)
        ClientEvent.offAll(config.EventRun.ON_COUNT_DOWN_START)
        ClientEvent.offAll(config.EventRun.ON_SHOW_RULE_BTN)
        ClientEvent.offAll(config.EventRun.ON_BOSS_HURT)

        ClientEvent.on(config.EventRun.WIDGET_FINISH,this.onWidgetFinishEvent.bind(this),this)
        ClientEvent.on(config.EventRun.WIDGET_FAIL,this.onWidgetFailEvent.bind(this),this)
        ClientEvent.on(config.EventRun.TOP_VIEW_CLOSE,this.onUiCloseEvent.bind(this),this)
        ClientEvent.on(config.EventRun.TOP_VIEW_FINISH,this.onUiFinishEvent.bind(this),this)
        ClientEvent.on(config.EventRun.TOP_VIEW_FAIL,this.onUiFailEvent.bind(this),this)
        ClientEvent.on(config.EventRun.ON_COUNT_DOWN_FAIL,this.onCountDownFailEvent.bind(this),this)
        ClientEvent.on(config.EventRun.ON_COUNT_DOWN_START,this.onStartCountDownEvent.bind(this),this)
    }

    public initGR(gr:game_run){
        this.mGameRun = gr;
        gameManager.Singleton  = this;
        this.mSceneManager.init(this)
        this.clearRes()
    }

    public clearRes(){
        gameManager.res_map.clear()
        gameManager.mp3_cache.clear()
    }

    public init(gr:game_run,data:scene_item_data[],callback=null){
        this.mGameRun = gr;
        gameManager.Singleton  = this;
        this.mSceneManager.init(this)
        this.mCurSceneIndex = main.Singleton.edit_scene_view.getCurSelectSceneIndex()
        // this.postLevelInfo(id,scene)
        // this.startLevelGame()
        // console.log("control.Singleton.get_bag_data().content",control.Singleton.get_bag_data())
        this.mGameData = data;
        if( this.mGameData.length<=0){
           return tools.showToast("错误的场景信息")
        }
        this.startLevelGame(callback)
    }

    public runGame(data:scene_item_data[]){
        this.mCurSceneIndex = 0;
        this.mGameData = data;
        if( this.mGameData.length<=0){
            return tools.showToast("错误的场景信息")
         }
         this.startLevelGame()
    }

    public onLaunch(call,delay=0.7){
        this.mGameRun.onlaunch(call,delay)
    }

    FilterChildScene(data:scene_item_data[]){
        let temp_scene = []
        for (let index = 0; index < data.length; index++) {
            const element = data[index];
            if(!element.is_child_scene){
                temp_scene.push(element)
            }
        }
        return temp_scene;
    }

    protected onDestroy(): void {
        ClientEvent.off(config.EventRun.WIDGET_FINISH,this.onWidgetFinishEvent.bind(this),this)
    }

    public startLevelGame(callback=null){
        this.initEvent()
        if(callback!=null) { callback() }
        console.log("this.mGameData",this.mGameData,this.mCurSceneIndex)
        this.mSceneManager.startLevelGame(this.mGameData[this.mCurSceneIndex])
        taskServce.initTask(this.mGameData[this.mCurSceneIndex]._task_data)
        this.scheduleOnce(()=>{
            this.startGame()
        },0.5)
        if(gameManager.Singleton.getLevelData()){
            this.mSceneManager.playMusic(this.mLevelData.piped_music,true)
        }
    }

    public loadSceneTask(data: task_data) {
        this.mGameRun.loadSceneTask(data)
    }

    public loadScene(pages: scene_item_data[],type:number){
        this.mGameRun.loadSceneLayer(pages,type)
    }

    public loadUi(ui_widge_list:widget_item_data[]){
        this.mGameRun.loadUILayer(ui_widge_list)
    }

    public loadTextSound(ui_widge_list:widget_item_data[]){
        this.mGameRun.loadTextSound(ui_widge_list)
    }

    public loadQuestion(ui_widge_list:widget_item_data[]){
        this.mGameRun.initQuestionList(ui_widge_list)
    }

    public initCountDownList(ui_widge_list:widget_item_data[]){
        this.mGameRun.initCountDownList(ui_widge_list)
    }

    public initTaskUi(data:task_data){
        this.mGameRun.initTaskUi(data)
    }

    public startGame(){
        taskServce.startFirstEvent()
    }

    public showCheck(call){
        this.mGameRun.showCheck(call)
    }

    public showLoadingLevel(){
        this.mGameRun.showLoadingLevel()
    }

    public hideLoadingLevel(){
        this.mGameRun.hideLoadingLevel()
    }

    public static getWidgetList(scene_data:scene_item_data):widget_item_data[]{
        let temp:widget_item_data[] = []
        for (let index = 0; index < scene_data.page_widget_list.length; index++) {
            const data = scene_data.page_widget_list[index];
            if(data.type<=4 ){
                temp.push(data)
            }
        }
        return temp;
    }

    public static getUIWidgetList(scene_data:scene_item_data){
        let temp:widget_item_data[] = []
        for (let index = 0; index < scene_data.page_widget_list.length; index++) {
            const data = scene_data.page_widget_list[index];
            if(data.type===config.Widget_Type_List.UI_TOP){
                if(data.att.top_data!=null&&data.att.top_data.top_ui_type!=config.top_view_type.__null){
                    temp.push(data)
                }
            }
        }
        return temp;
    }

    public static getQuestionwidgetList(scene_data:scene_item_data){
        let temp:widget_item_data[] = []
        for (let index = 0; index < scene_data.page_widget_list.length; index++) {
            const data = scene_data.page_widget_list[index];
            if(data.type===config.Widget_Type_List.QUESTION_SELECT){
                if(data.att.question_select!=null){
                    temp.push(data)
                }
            }
        }
        return temp;
    }

    public static getTextSoundWidgetList(scene_data:scene_item_data){
        let temp:widget_item_data[] = []
        for (let index = 0; index < scene_data.page_widget_list.length; index++) {
            const data = scene_data.page_widget_list[index];
            if(data.type===config.Widget_Type_List.TEXT_SOUND){
                if(data.att.text_sound_data!=null){
                    temp.push(data)
                }
            }
        }
        return temp;
    }

    public static getCountDownWidgetList(scene_data:scene_item_data){
        let temp:widget_item_data[] = []
        for (let index = 0; index < scene_data.page_widget_list.length; index++) {
            const data = scene_data.page_widget_list[index];
            if(data.type===config.Widget_Type_List.COUNT_DOWN){
                if(data.att.count_down!=null){
                    temp.push(data)
                }
            }
        }
        return temp;
    }

    public static getCacheSpriteFrameByName(sfName:string){
        // return control.res_map.get(sfName)
        return gameManager.res_map.get(sfName)
    }
    public static getCacheSoundByName(sfName:string){
        // return control.mp3_cache.get(sfName)
        return gameManager.mp3_cache.get(sfName)
    }
    public static initUiBaseAtt(node:Node,att:ui_att_item){
        node.getComponent(UITransform).setContentSize(new Size(att.width,att.height))
        node.position = new Vec3(att.x,att.y);
        node.getComponent(Sprite).spriteFrame = gameManager.getCacheSpriteFrameByName(att.res)
    }

    onWidgetFinishEvent(widget_id:number){
        taskServce.onWidgetFinishEvent(widget_id)
    }

    onWidgetFailEvent(widget_id:number){
        taskServce.onWidgetFailEvent(widget_id)
    }

    onUiCloseEvent(event_id:number){
        taskServce.extEventByEventId(event_id)
    }

    onUiFinishEvent(event_id:number){
        taskServce.extEventByEventId(event_id)
    }

    onUiFailEvent(event_id:number){
        taskServce.extEventByEventId(event_id)
    }

    onCountDownFailEvent(event_id:number){
        taskServce.extEventByEventId(event_id)
    }

    onStartCountDownEvent(event_id:number){
        taskServce.extEventByEventId(event_id)
    }
    
    exeEvent(event_id:number){
        taskServce.extEventByEventId(event_id)
    }

    exeSuccessTriggerEvent(trigger_event_id:number) {
        taskServce.exeSuccessTriggerEvent(trigger_event_id)
    }

    exeNextDelayEvent(event_item:event_item) {
        taskServce.exeNextDelayEvent(event_item)
    }

    showFindRuleTips(){
        this.mGameRun.showFindRuleTips()
    }

    showTips(){
        this.mGameRun.showTips()
    }

    showRule(){
        this.mGameRun.showRule()
    }

    getSceneManager(){
        return this.mSceneManager;
    }

    IsOpenRuleStatus(){
        return taskServce.guo_ju_qing_binding_event_id==-1;
    }

    public checkWidgetList(list:other_widget_finish_listen_item[]):number{
        let event_id = -1;
        for (let index = 0; index < list.length; index++) {
            const item = list[index];
            let isFinish =  this.mGameRun.isCurScenePageCheckWidgetFinish(item.widget_id)
            if(!isFinish){
                event_id = item.event_id;
                break;
            }
        }
        return event_id;
    }

    public isCurScenePageCheckWidgetFinish(widget_id:number){
        return this.mGameRun.isCurScenePageCheckWidgetFinish(widget_id);
    }

    public isCurScenePageCheckWidgetShow(widget_id:number){
        return this.mGameRun.isCurScenePageCheckWidgetShow(widget_id);
    }

    //点击按钮音效
    public sys_click_button_music(){
        if(gameManager.sys_data!=null){
            this.mSysSound.playSound(gameManager.sys_data.content.sys_click_button_music)
        }
    }


    // //失败吓人音效
    // public sys_fail_scary_music(){
    //     if(gameManager.sys_data!=null){
    //         this.mSysSound.playSound(gameManager.sys_data.content.sys_fail_scary_music)
    //     }
    // }

    //失败后攻击音效
    public sys_fail_attack_music(){
        if(gameManager.sys_data!=null){
            this.mSysSound.playSound(gameManager.sys_data.content.sys_fail_attack_music)
        }
    }

    //失败提示音效
    public sys_fail_prompt_music(){
        if(gameManager.sys_data!=null){
            this.mSysSound.playSound(gameManager.sys_data.content.sys_fail_prompt_music)
        }
    }

    //正确通关音效
    public sys_success_complete_music(){
        if(gameManager.sys_data!=null){
            this.mSysSound.playSound(gameManager.sys_data.content.sys_success_complete_music)
        }
    }

    //点击正确细节音效
    public sys_click_correct_detail_music(){
        if(gameManager.sys_data!=null){
            this.mSysSound.playSound(gameManager.sys_data.content.sys_click_correct_detail_music)
        }
    }

    public getCurSceneIndex(){
        return this.mCurSceneIndex;
    }

    //保存编辑场景
    public static requestSaveEditScene() {
        tools.show_loading(()=>{
            // let data = new FormData()
            let content = control.Singleton.get_bag_data().content
            let zujian_id = config.last_id;
            let id = control.Singleton.get_bag_data().id;
            // data.append("content",JSON.stringify(content))
            // data.append("zujian_id",zujian_id+"")
            // data.append("id",id+"")
            console.log("btn_save",content)
            let request_data = {"content":JSON.stringify(content),"zujian_id":zujian_id,"id":id}
            http.post("/tool/mysnote/save",  request_data, (err,data)=>{
                if(!err){
                    tools.showToast("保存成功!")
                }
                tools.hide_loading()
            })
        })
    }

    public static LookVideoCallBack(call){
        if(call!=null){
            call()
        }
    }

    public getCurSceneLayerPage(){
        return this.mGameRun.getCurSceneLayerPage()
    }
}


