
const {ccclass, property, requireComponent} = cc._decorator;
import GameData from "./GameData";
import { StorageMessage } from "./Storage";

@ccclass
export default class NewClass extends cc.Component {

    start () {
        this.Authentication();
    }

    //鉴权，判断有无缓存userid,有的话判断是否过期，没有的话重新获取userid 并且缓存上
    private Authentication(){
        let name = "user_" + GameData._instance.GM_INFO.gameId;
        let data = StorageMessage.getStorage(name);
        if(data == "undifend" || data==null || data == ""){
            console.log("没缓存");
            this.setUserId(name);
        }
        else{
            console.log("有缓存");
            let timestamp = parseInt(new Date().getTime()/1000 + "");
            if((timestamp - data.time) > 86400){
                console.log("缓存过期");
                this.setUserId(name);
                return;
            }
            GameData._instance.GM_INFO.userId = parseInt(data.userId);
        }
    }
    //设置userId,链接有获取，没有跳转授权
    private setUserId(name){
        GameData._instance.GM_INFO.userId = this.getUserId();
        if(GameData._instance.GM_INFO.userId == null){
            console.log("链接没ID准备跳转");
            let url = "http://api.sparkus.cn/api/user/auth/login?domain=hui32579WdYPsgYq&callback="+location.href;
            window.location.href = url;
        }
        else{
            let timestamp = parseInt(new Date().getTime()/1000 + "");
            let idData = {
                userId: GameData._instance.GM_INFO.userId + "",
                time: timestamp
            }
            StorageMessage.setStorage(name,idData);
            console.log("有ID：",GameData._instance.GM_INFO.userId);
            GameData._instance.GM_INFO.userId = parseInt(GameData._instance.GM_INFO.userId);
        }
    }
    //获取user id 有参数为获取gameid userid 时间戳， 无参数为只获取链接尾缀上的userId
    private getUserId() {    
        let pathStr = window.location.search;
        let arr=pathStr.split("&");
        if (pathStr.length>= 0&&arr.length>0) {
            let arr2=[];
            arr.map(item=>{
                arr2.push(item.split("=")[1])
            })
            return arr2[0];
        } else {
            return null
        }
    }
    //开始游戏，跳转至引导页面
    startGame(){
        cc.director.loadScene("GuideScene");
    }
    //备用，用来测试跳转 指定关卡
    clickBtn(event,data){
        GameData._instance.GM_INFO.custom = parseInt(data);
        cc.director.loadScene("GameScene");
    }   
    //打开排行榜
    openRank(){
        cc.director.loadScene("RankScene");
    }
    
    protected update(dt: number): void {
    }
}
