import { _decorator, Component, EventTouch, instantiate, JsonAsset, Label, Node, Prefab, sys, UITransform, Vec3 } from 'cc';
import { http } from '../../http';
import { gameManager } from '../gameManager';
import { LevelInfoMessage, LevelMessage, scene_item_data } from '../../../data/data';
import { level_list_item } from './level_list_item';
import { config } from '../../config';
import { tools } from '../../tools';
const { ccclass, property } = _decorator;

@ccclass('game_list')
export class game_list extends Component {
    @property(Node) btn_back:Node = null;
    @property(Node) lab_cur_select_page:Node = null;
    @property(Node) content:Node = null;
    @property(Prefab) game_level_item:Prefab = null;
    private m_back_call = null;
    private m_loading_finish_call = null;
    private m_data:LevelMessage = null;
    private origin_pos:Vec3 = Vec3.ZERO;
    private x_len:number = 0;
    private onTouchActive:boolean = true;
    public initView(finish_call,call_back){
        this.m_back_call = call_back;
        this.m_loading_finish_call = finish_call;
        this.btn_back.off(Node.EventType.TOUCH_END)
        this.btn_back.on(Node.EventType.TOUCH_END,()=>{
            if(this.m_back_call!=null){
                this.m_back_call()
            }
            gameManager.Singleton.sys_click_button_music()
        })
        this.loadView()
    }

    public loadView(){
        let user_data = gameManager.getUserData()
        let url = http.getGameList(user_data.select_page)
        http.run_get(url,(err,data)=>{
            if(!err){
                let msg:LevelMessage  = JSON.parse(data)
                this.initGameList(msg)
                if(this.m_loading_finish_call!=null){
                    this.m_loading_finish_call()
                }
            }
        })
    }

    public initGameList(msg:LevelMessage){
        this.m_data = msg;
        this.lab_cur_select_page.getComponent(Label).string = `${gameManager.getUserData().select_page}/${this.getAllPage()}`
        this.content.removeAllChildren()
        for (let index = 0; index <  this.m_data.content.list.length; index++) {
            const element = this.m_data.content.list[index];
            let item = instantiate(this.game_level_item)
            item.parent = this.content;
            item.getComponent(level_list_item).initView(this.onItemClick.bind(this),element)
        }
        this.content.on(Node.EventType.TOUCH_MOVE,(et:EventTouch)=>{
            let p = new Vec3(et.getUILocation().x,et.getUILocation().y)
            let n_p = this.content.parent.getComponent(UITransform).convertToNodeSpaceAR(p)
            let pos = this.content.parent.getComponent(UITransform).convertToWorldSpaceAR(this.content.position)
            if(this.x_len==0){
                this.x_len = (et.getUILocation().x - pos.x)*2;
            }
            this.content.position = new Vec3(n_p.x-this.x_len ,this.content.position.y);
        })
        this.content.on(Node.EventType.TOUCH_CANCEL,()=>{
            this.x_len = 0;
            this.content.position = new Vec3(this.origin_pos.x,this.content.position.y);
        })
        this.content.on(Node.EventType.TOUCH_END,()=>{
            this.x_len = 0;
            if((this.content.position.x-this.origin_pos.x)>300){ //说明是向右方向滑动
                this.onUpPage()
                this.content.position = new Vec3(this.origin_pos.x,this.content.position.y);
                return
            }

            if((this.content.position.x-this.origin_pos.x)<-300){ //说明是向左方向滑动
                this.onNextPage()
                this.content.position = new Vec3(this.origin_pos.x,this.content.position.y);
                return
            }
            this.content.position = new Vec3(this.origin_pos.x,this.content.position.y);
        },this,true)
    }

    updatePage(page:number){
        this.onTouchActive = false;
        this.content.removeAllChildren()
        gameManager.getStaticUserData().select_page = page;
        gameManager.saveUserData()
        this.content.off(Node.EventType.TOUCH_MOVE)
        this.content.off(Node.EventType.TOUCH_CANCEL)
        this.content.off(Node.EventType.TOUCH_END)
        let url = http.getGameList(gameManager.getStaticUserData().select_page)
        http.run_get(url,(err,data)=>{
            if(!err){
                let msg:LevelMessage  = JSON.parse(data)
                this.initGameList(msg)
            }
        })
        this.unscheduleAllCallbacks()
        this.scheduleOnce(()=>{
            this.onTouchActive = true;
        },1)
    }

    onUpPage(){
        let page = gameManager.getStaticUserData().select_page - 1;
        if(page<1){
            return
        }
        this.updatePage(page)
        // console.log("onUpPage")
    }

    onNextPage(){
        let page = gameManager.getStaticUserData().select_page + 1;
        if(page>this.getAllPage()){
            return
        }
        this.updatePage(page)
        // console.log("onNextPage")
    }

    onItemClick(item:level_list_item){
        if(!this.onTouchActive){
            return
        }
        if(!item.getIsUnLock()){
            tools.show_dialog("是否解锁?",()=>{
                item.UnLock()
            })
            return;
        }
        let call = ()=>{
            let url = http.get_level_info(item.getData().id)
            gameManager.Singleton.showLoadingLevel()
            http.run_get(url,(err,data)=>{
                if(!err){
                    let _data:LevelInfoMessage = JSON.parse(data)
                    if(_data.code===config.MSG_CODE.SUCCESS){
                        if(_data.content.content.length>0){
                            let list:scene_item_data[] = JSON.parse(_data.content.content.toString())
                            _data.content.content = list;
                        }
                        // console.log(" _data.content.content ",_data.content.content )
                        gameManager.loadSceneRes(_data.content.id,_data.content.content.length,()=>{
                            // console.log("全部加载完成")
                            gameManager.Singleton.setLevelData(item.getData())
                            gameManager.Singleton.runGame(_data.content.content)
                            gameManager.Singleton.hideLoadingLevel()
                            this.hide()
                        })
                  
                    }else{
                        tools.showToast("错误码："+_data.code)
                    }
                }else{
                    console.log("进入关卡错误：",err)
                }
            })
        }
        if(item.getData().category_id===1){
            gameManager.Singleton.showCheck(()=>{
                call()
            })
        }else{
            call()
        }
        // console.log("onItemClick",item)
    }

    hide(){
        this.node.active = false;
    }

    getAllPage(){
        if(this.m_data.content.tool_number<=6){
            return 1;
        }
        return Math.floor(this.m_data.content.tool_number/6)
    }
}


