import { gameMethod } from "../../../common/gameMethod";
import Config from "../../../Config";
import GameController from "../../../GameController";
import EventMng from "../../../manager/EventMng";
import { ReqPlatLogin } from "../../../shared/plat/PtlPlatLogin";
import { ReqPlayerLogin } from "../../../shared/player/PtlPlayerLogin";
import ThinkingDataMgr from "../../../utils/ThinkingDataMgr";
import { GameEvent, LoadEvent, NetworkEvent } from "../../const/EventConst";
import { DayTipsKey, GameErrCode, PlatformType, ReportRoleType } from "../../const/TypeConst";
import GameDataCenter from "../../GameDataCenter";
import { LoginModelData } from "./LoginModelData";


export default class LoginModel extends LoginModelData {
    KEY_ACCOUNT = 'login';
    KEY_POLICY = 'policy_agree';
    KEY_LAST_LOGIN_TIME = 'KEY_LAST_LOGIN_TIME';
    uuid: string

    // 设定进入游戏的服务器ID
    enterGameSid: string = ""
    constructor() {
        super('login');
        this.enterGameSid = ""
    }

    //隐私协议政策
    savePolicy(val: boolean) {
        this.Set(this.KEY_POLICY, val ? "1" : "0")
        this.Save()
    }
    getPolicy(): boolean {
        let result = this.Query(this.KEY_POLICY, '1');
        if (Config.policy == "0") {
            result = this.Query(this.KEY_POLICY, '0');
        }
        return result == "1"
    }

    /**缓存账号到本地 */
    saveAccount(account: string) {
        this.Set(this.KEY_ACCOUNT, account);
        this.Save();
    }

    /**从本地读取缓存账号 */
    getAccount() {
        return this.Query(this.KEY_ACCOUNT, '');
    }

    // 平台登录
    async sendPlatLoginGame(param: ReqPlatLogin) {
        let ret = await GameDataCenter.loginServer.ReqApi("plat/PlatLogin", param);
        if (ret.isSucc) {
            EventMng.emit(LoadEvent.LOAD_PROGRESS, 0.5, "login")
            GameDataCenter.plat.instance.openId = ret.res.openId;
            GameDataCenter.plat.instance.loginParams = [ret.res.token]
            GameDataCenter.plat.instance.login()
        } else {
            if (gameMethod.isEmpty(ret.err) || gameMethod.isEmpty(ret.err.message)) {
                GameDataCenter.plat.showErrDialog(GameErrCode.errGameLoginPlayer)
                EventMng.emit(GameEvent.LOGIN_ACCOUNT_FAIL);
            }
        }
    }

    // 账号登录
    async sendLoginGame(param: ReqPlayerLogin) {
        let ret = await GameDataCenter.loginServer.ReqApi("player/PlayerLogin", param);
        if (ret?.isSucc) {
            CC_PREVIEW && console.log("玩家登录成功", ret);
            this.playerInfo = ret.res
            GameDataCenter.gameServer.Init(ret.res.wsUrl);
            await GameDataCenter.gameServer.Connect();
            EventMng.emit(GameEvent.LOGIN_ACCOUNT_SUCC);
            EventMng.emit(NetworkEvent.NET_MSG_REGISTER);
        } else {
            if (gameMethod.isEmpty(ret.err) || gameMethod.isEmpty(ret.err.message)) {
                GameDataCenter.plat.showErrDialog(GameErrCode.errGameLoginPlayer)
                EventMng.emit(GameEvent.LOGIN_ACCOUNT_FAIL);
            }
        }
    }
    // 点击进入游戏按钮,并进入游戏
    async sendEnterGame(sid: string) {
        let ret = await GameDataCenter.gameServer.ReqApi("user/UserLogin", {
            uid: this.playerInfo.uid,
            sid: sid,
            token: this.playerInfo.token
        });
        if (ret?.isSucc) {
            GameDataCenter.user.setUserInfo(ret.res);
            GameController.network.stopRequest = false
            ThinkingDataMgr.TDLogin(this.uuid);//数数数据上传
            if (ret.res && ret.res.regtime == ret.res.lastlogin) {
                GameDataCenter.plat.instance.reportRole(ReportRoleType.create)
            }
            GameDataCenter.plat.instance.reportRole(ReportRoleType.online)
            EventMng.emit(GameEvent.LOGIN_USER_SUCC);
            // GameDataCenter.zhaocai.upRedState()
            //电魂角色上报
            if (window['dhSDK']) {
                window['dhSDK'].uploadRoleInfo({
                    type: "LOGIN_GAME", // 登录游戏服时传LOGIN_GAME，创角时传CREATE_ROLE，升级时传LEVEL_UP，充值成功时传PAY_SUCCESS
                    areaId: parseInt(GameDataCenter.user.userInfo?.sid), // 游戏大区ID，若游戏无大区概念，可不填，默认值为 1，表示初始大区编号
                    areaName: this.playerInfo.qufuList[GameDataCenter.user.userInfo?.sid].name, // 游戏大区名称
                    roleId: GameDataCenter.user.uuid, // 角色ID，若游戏无角色概念，可不填，默认值同 accountId 账号ID
                    roleName: GameDataCenter.user.userInfo?.name, // 角色名
                    roleLevel: GameDataCenter.user.userInfo?.level, // 角色等级，若游戏无角色及等级概念，可填关卡等级或不填，默认值为 1
                    roleVipLevel: 1, // 角色VIP等级
                }, (params: any) => {
                    console.log(params);
                });
            }
        } else {
            // if (gameMethod.isEmpty(ret.err) || gameMethod.isEmpty(ret.err.message)) {
            //     GameDataCenter.plat.showErrDialog(GameErrCode.errGameLoginUser)
            //     EventMng.emit(GameEvent.LOGIN_USER_FAIL);
            // }
        }

    }
}