import { StorageKey } from "./StorageData";

/**
 * @description 登录数据
 * @author 邹勇
 */
export class LoginData {

    public loadResCompelete: boolean = false;

    /** 是否登录 */
    public isLogin: boolean = false;

    public sessionKey: string = '';

    public randomKey: string = "abcdefghijklopqrstuvwxyzabcdefgh";

    /** 玩家唯一id */
    public uin: string = '';

    /** 玩家临时id */
    public tempUin: string = '';

    public loginTicket: string = '';

    public isFirstIn: boolean;

    public isNew: boolean;

    /** 是否授权 */
    public isAuth: boolean;

    /** 服务协议 */
    public rule_data: string[];

    /** 隐私协议 */
    public privacy_data: string[];

    /**
     * 初始化本地配置
     * @returns 
     */
    public async loadLocalRes() {
        let result = await mk.loader.load("data/rule_data", cc.JsonAsset);
        if (result && result.json) {
            this.rule_data = result.json.server;
            this.privacy_data = result.json.privacy;
        }

        result = await mk.loader.load("data/guide_data", cc.JsonAsset);
        if (result && result.json) {
            gData.guideData.init(result.json);
            this.loadResCompelete = true;
        }
    }

    /**
     * 初始化
     */
    public init() {
        let uin = mk.storage.getStorage(StorageKey.uin);
        this.uin = uin ? uin : "";
        let sessionKey = mk.storage.getStorage(StorageKey.sessionKey);
        this.sessionKey = sessionKey ? sessionKey : "";
    }

    /**
     * 登录流程 
     * @description initApp-->initAd-->connect-->wxLogin-->checkLogin-->getAccountInfo
     */
    public async login() {

        //有登录记录直接跳转到登录流程最后一步
        if (this.sessionKey != '' && this.uin != '') {
            console.log("=== login 有登录记录直接跳转到登录流程最后一步");
            this.getAccountInfo();
            return;
        }
        else {
            console.log("=== login 无登录记录");
            this.connect();
        }

    }

    /**
     * 链接 
     * @description 获取临时的uin
     */
    private async connect() {
        //connect
        this.randomKey = mk.encrypt.randomString();
        let data: any = {
            "mac": gData.appData.mac,
            "psk": this.randomKey,
            "appId": gData.appData.appId
        }

        let response = await mk.http.sendRequest('connectTest', 'POST', JSON.stringify(data));
        if (response.errcode != 0) {
            return;
        }
        data = mk.encrypt.decrypt(response.encrypt, this.randomKey, gData.appData.appId);
        console.log("[FC]connectTest decryptData", data);
        this.tempUin = JSON.parse(data).tmp_uin;
        mk.storage.setStorage(StorageKey.uin, this.tempUin);
        this.wxLogin();
    }

    public async wxLogin() {
        //wxLogin
        let data;
        let encode;
        if (gData.wechatData.code != null) {
            //微信登录
            encode = mk.encrypt.encrypt(JSON.stringify({ "code": gData.wechatData.code }), this.sessionKey, gData.appData.appId);
            data = {
                "uin": this.uin,
                "encrypt": encode
            };
        }
        else {
            //游客登录
            encode = mk.encrypt.encrypt(JSON.stringify({ "code": '' }), this.randomKey, gData.appData.appId);
            data = {
                "uin": this.tempUin,
                "encrypt": encode
            };
        }
        let response = await mk.http.sendRequest('wxlogin', 'POST', JSON.stringify(data), false, false);
        if (response.errcode != 0) {
            if (response.errcode == -10003 || response.errcode == -20003) {
                //清除缓存
                this.reload();
            }
            return;
        }
        if (gData.wechatData.code != null) {
            data = mk.encrypt.decrypt(response.encrypt, this.sessionKey, gData.appData.appId);
        }
        else {
            data = mk.encrypt.decrypt(response.encrypt, this.randomKey, gData.appData.appId);
        }
        data = JSON.parse(data);
        this.loginTicket = data.login_ticket;
        console.log("[FC]wxLoginTest decrypt", data);
        mk.storage.setStorage(StorageKey.loginTicket, this.loginTicket);

        let isFirstIn = mk.storage.getStorage(StorageKey.isFirstIn);
        if (isFirstIn == null) {
            this.isFirstIn = true;
            mk.storage.setStorage(StorageKey.isFirstIn, 1);
        }

        if (this.uin != data.uin) {
            this.uin = data.uin;
            this.isNew = false;
        }
        else {
            this.isNew = true;
        }
        mk.storage.setStorage(StorageKey.uin, this.uin);
        this.checkLogin();
    }

    /**
     * 检测登录
     * @returns 
     */
    private async checkLogin() {
        //checkLogin
        let tmp_key = '';
        if (gData.wechatData.code != null) {
            tmp_key = this.sessionKey;
        }
        else {
            tmp_key = mk.encrypt.randomString();
        }

        let data = {
            "tmp_key": tmp_key,
            "uin": this.uin,
            "login_ticket": this.loginTicket,
            "appId": gData.appData.appId
        }
        let response = await mk.http.sendRequest('checklogin', 'POST', JSON.stringify(data));
        if (response.errcode != 0) {
            return;
        }
        let decryptData;
        if (gData.wechatData.code != null) {
            decryptData = mk.encrypt.decrypt(response.encrypt, this.sessionKey, gData.appData.appId);
        }
        else {
            decryptData = mk.encrypt.decrypt(response.encrypt, tmp_key, gData.appData.appId);
        }

        let parseData = JSON.parse(decryptData);
        this.sessionKey = parseData.session_key;
        console.log("[FC]checkLogin decrypt", parseData);
        mk.storage.setStorage(StorageKey.sessionKey, this.sessionKey);
        this.getUserInfo();
    }

    private async getUserInfo() {
        
        // if (gData.wechatData.code != null) {
        //     if (this.isNew) {//玩过此游戏并且本地数据是本机的
        //         this.getAccountInfo();
        //     }
        //     else {//玩过此游戏 但 本地数据不是本账户的 清空数据 重新登录游戏
        //         this.isNew = false;
        //         gData.wechatData.code = null;
        //         this.reload();
        //     }
        // }
        // else {
        //     this.getAccountInfo();
        // }

        this.getAccountInfo();
    }

    private async getAccountInfo() {
        // let nickname = mk.storage.getStorage(StorageKey.nickname);
        // if (nickname) {
        //     gData.wechatData.nickName = nickname;
        // }
        // else {
            let aa = {
                "uin": this.uin,
                "login_ticket": this.loginTicket
            };

            let data: any = {
                "uin": this.uin,
                "encrypt": mk.encrypt.encrypt(JSON.stringify(aa), this.sessionKey, gData.appData.appId)
            };

            let response = await mk.http.sendRequest('user', 'POST', JSON.stringify(data), false, false);
            if (response.errcode != 0) {
                if (response.errcode == -10003 || response.errcode == -20003) {
                    //清除缓存
                    this.reload();
                }
                return;
            }
            response = mk.http.checkData(response, true);
            data = response.data;
            mk.console.logSingle("[FC] getAccountInfo decrypt", data);
            this.isAuth = data.is_auth;
            if (this.isAuth) {
                gData.wechatData.nickName = data.nickname;
                gData.wechatData.avatar = data.headimgurl;
                gData.wechatData.unionid = this.uin;
                gData.gameData.init_head = true;
                mk.storage.setStorage(StorageKey.isAuth, 1);
                mk.storage.setStorage(StorageKey.nickname, gData.wechatData.nickName, false);
                mk.storage.setStorage(StorageKey.avatar, gData.wechatData.avatar, false);
            }

        // }

        //获取游戏数据
        gData.gameData.init();
    }

    /**
     * 本地数据不是本账户的 清空数据 重新登录游戏
     */
    public reload() {
        let path = cc.sys.localStorage.getItem('HotUpdateSearchPaths');
        gData.storageData.clear();
        cc.sys.localStorage.setItem('HotUpdateSearchPaths', path);
        cc.audioEngine.stopAll();
        //调用Android的更好
        cc.game.restart();
    }
}