import { _decorator, Component, Node } from 'cc';
import JNLayerBase from '../../../../extensions/ngame/assets/ngame/ui/base/JNLayerBase';
import { API } from '../../consts/API';
import { EditBox } from 'cc';
import { app } from '../../App';
import { GUI } from '../UIConfig';
import { StorageData, StorageEnum } from '../../consts/GData';
import { Env, EnvCurrent } from '../../Env';
const { ccclass, property } = _decorator;

@ccclass('LoginView')
export class LoginView extends JNLayerBase {

    resolve:(token:string) => void;

    @property(EditBox)
    account:EditBox;
    @property(EditBox)
    password:EditBox;

    onJNLoad(resolve?: (token:string) => void): void {
        super.onJNLoad();
        this.resolve = resolve;
        
        //如果是服务器则取Windows账号密码
        if(EnvCurrent == Env.Server){
            this.account.string = window['GUser'];
            this.password.string = window['GPassworld'];
            this.onClickLogin();
        }
    }


    //点击登录
    async onClickLogin(){
        //校验
        if(!(this.account.string.length) || !(this.password.string.length)){
            app.layer.Open(GUI.Tips,{text:"请输入账号密码"});
            return;
        }

        //登录账号
        let info = await API.UserLogin(this.account.string,this.password.string);
        if(info){
            app.layer.Open(GUI.Tips,{text:"登录成功"});
            //保存Token
            StorageData.set(StorageEnum.Token,info.token);
            this.resolve(info.token);
            this.onJNClose();
        }
    }

    //点击注册账号
    async onClickRegister(){
        //注册账号
        let info = await API.UserRegister();
        //显示提示
        app.layer.Open(GUI.Tips,{text:"注册成功"});
        //显示账号和密码
        this.account.string = `${info.userId}`;
        this.password.string = info.userPass;
    }

}


