import { Framework } from "../../framework/Framework";
import { ObjectUtil } from "../../framework/util/ObjectUtil";
import { StringUtil } from "../../framework/util/StringUtil";
import { GameEvent } from "./GameEvent";

interface Account {
    openId: string;
    openKey: string;
    sdkUid;
    cdkeyUrl: string;
    version: string;
    cdnUrl: string;
    bulletin: string;
    platform: string;
    serverOpenTime: number;
    serverOpenHour: number;
    white: number;
    openCdkey: number;
    openLogout: number;
    download: string;
}
//账号角色 不是游戏角色
interface Role {
    sid: number;
    headpic: number;
    role_name: string;
    uid: string;
    lv: number;
    last_time: string;
    name?: string;
    status?: number;
    host?: string;
    gs?: number;
}

interface Server {
    sid: number;
    name: string;
    status: number;
    host: string;
    gs: number;
}

// type ServerData = {
//     role_list?: { id: string; pic: string; name: string; uid: string; lv: string; last_time: string }[];
//     server_list?: { id: string; name: string; status: string; host: string }[];
//     lastsid?: number;
// };

class Data {
    private _class_id = StringUtil.getUUID(32);
    //需要保存的数据
    save_data = new Map<string, any>();

    UserID: any = null;

    private _roleServers: Role[] = [];
    private _servers: Server[] = [];
    private _recmdServers: Server[] = [];
    // 服务器校对时间 毫秒
    private _serverCheckTime: number = 0;

    //账号信息
    private _accountData: Account = {
        openId: '',
        openKey: '',
        sdkUid: '',
        cdkeyUrl: '',
        version: '',
        cdnUrl: '',
        bulletin: '',
        platform: '',
        serverOpenTime: 0,
        serverOpenHour: 0,
        white: 0,
        openCdkey: 0,
        openLogout: 0,
        download: '',
    };
    //最后一次登录服id
    // private _sid: number = this.save_locally('lastsid',null,-1);;
    private _sid: number = -1;
    //推荐区域
    private _areaId: string = '1';


    _saveData(key: string, value: any) {
        this.save_data.delete(key);
        if (typeof value === 'object') {
            try {
                if (value instanceof Map) {
                    let temp = ObjectUtil.mapToObject(value)
                    value = JSON.stringify(temp);
                } else {
                    value = JSON.stringify(value);
                }
            } catch (e) {
                console.error(`解析失败,str = ${value}`);
                return;
            }
        } else {
            value = value + "";
        }
        this.save_data.set(key, value);
        Framework.storage.set('save_data', this.save_data);
    }

    private _mapToObject(map: any) {
        let obj = {};
        for (let [k, v] of map) {
            obj[k] = v;
        }
        return obj;
    }

    // 获取服务器时间 毫秒
    get serverTime() {
        let now = new Date();
        let time = now.getTime()
        return this._serverCheckTime+time;
    }
    set serverTime(value) {
        let now = new Date();
        let time = now.getTime() 
        
        this._serverCheckTime = value - time;
    }


    parseLoginData(data) {
        this._roleServers = [];
        this._servers = [];
        this._recmdServers = [];
        this.initAccount(data);
        this.initRoles(data.role_list);
        if (data.server_list) {
            this.initServers(data.server_list);
        }
        if (data.lastsid && data.lastsid > 0) {
            this.setSid(data.lastsid, true);
        }
    }

    setSid(sid: number, flag: boolean): void {
        this._sid = sid;
        if (flag) {
            this._saveData('lastsid',sid);
        }
    }

    getSid(){
        return this._sid;
    }

    setAreanId(areanId: string): void {
        this._areaId = areanId;
    }

    getAreanId(){
        return this._areaId;
    }

    private initAccount(data) {
        if (data.openid) {
            this._accountData.openId = data.openid;
        }
        if (data.openkey) {
            this._accountData.openKey = data.openkey;
        }
        if (data.sdkuid) {
            this._accountData.sdkUid = data.sdkuid;
        }
        if (data.cdkey) {
            this._accountData.cdkeyUrl = data.cdkey;
        }
        if (data.version) {
            this._accountData.version = data.version;
        }
        if (data.cdn) {
            this._accountData.cdnUrl = data.cdn;
        }
        if (data.bulletin) {
            this._accountData.bulletin = data.bulletin;
        }
        if (data.platform) {
            this._accountData.platform = data.platform;
        }
        if (data.server_open_time) {
            this._accountData.serverOpenTime = data.server_open_time;
        }
        if (data.server_open_hour) {
            this._accountData.serverOpenHour = data.server_open_hour;
        }
        if (data.white) {
            this._accountData.white = data.white;
        }
        if (data.open_cdkey) {
            this._accountData.openCdkey = data.open_cdkey;
        }
        if (data.open_logout) {
            this._accountData.openLogout = data.open_logout;
        }
        if (data.download) {
            this._accountData.download = data.download;
        }
    }

    private initRoles(roleList?: { id: string; pic: string; name: string; uid: string; lv: string; last_time: string }[]): void {
        if (roleList) {
            for (const key in roleList) {
                let v = roleList[key];
                const t: Role = {
                    sid: parseInt(v.id),
                    headpic: parseInt(v.pic),
                    role_name: v.name,
                    uid: v.uid,
                    lv: parseInt(v.lv),
                    last_time: v.last_time,
                };
                this._roleServers.push(t);
            }
        }
    }

    private initServers(serverList: { id: string; name: string; status: string; host: string }[]): void {
        for (const key in serverList) {
            let v = serverList[key];
            const tab: Server = {
                sid: parseInt(v.id),
                name: v.name,
                status: parseInt(v.status),
                host: v.host,
                gs: parseInt(v.status) * 10000 + parseInt(v.id),
            };

            this._servers.push(tab);

            if (tab.status === 2) {
                this._recmdServers.push(tab);
            }

            for (const role of this._roleServers) {
                if (role.sid === tab.sid) {
                    role.name = tab.name;
                    role.status = tab.status;
                    role.host = tab.host;
                    role.gs = tab.gs;
                    break;
                }
            }
        }

        this._roleServers.sort((a, b) => (a.last_time > b.last_time ? -1 : 1));
        this._servers.sort((a, b) => (a.gs > b.gs ? -1 : 1));
        this._recmdServers.sort((a, b) => (a.gs > b.gs ? -1 : 1));
    }

    getAccountData() {
        return this._accountData;
    }

    getAllServers() {
        return this._servers;
    }


    getRoleServers() {
        return this._roleServers;
    }


    getRecmdServers() {
        return this._recmdServers;
    }

    getServerBySid(sid: number): Server | undefined {
        let server = this._servers.find(v => v.sid === sid);

        if (!server) {
            if (this._servers.length <= 0) {
                // PromptMgr.showTips(Util.getString('110573'));
            }
            this._sid = this._servers[0]?.sid;
            server = this._servers[0];
        }

        return server;
    }
}

export let AccountData = new Data;