const weChat = require('../net/WeChat');
const LoginApi = require('../net/LoginApi');
const HomeApi = require("../net/HomeApi");
const Api = require('../net/Api');
const DWTool = require('../utils/DWTool');
const GameModule = require('../utils/GameModule');

cc.Class({
    extends: cc.Component,

    properties: {

        preloadProgress: cc.ProgressBar,
        preloadLabel: cc.Label,
        loginLabel: cc.Label,
        updateUI: cc.Node,

        _updating: false,           //是否正在更新
        _canRetry: false,           //能否重新获取更新
        _preloaded: false,          //是否已经预加载完资源
    },

    onLoad() {
        if (CC_WECHATGAME) {
            window.wx.postMessage({ //初始化的时候关闭子域刷新
                messageType: 8,
            });
        }

        this.loadAllGameRes();
    },

    loadAllGameRes() {
        this.updateUI.active = true;

        this.preloadRes = false;
        this.preloadProgress.progress = 0;
        this.loadScene();

        // 加载图片资源完成, 开始加载首页场景    
        cc.director.preloadScene("game", () => {
            cc.log("Next scene preloaded");

            this.preloadProgress.progress = 0;

            this.loginLabel.string = '正在拼命加载游戏资源...'

            // 加载需要的图片资源
            cc.loader.loadResDir("./textures/building", cc.Texture2D, (completeCount, totalCount, res) => {
                this.preloadRes = true
                // 正在加载图片资源中...
                this.preloadProgress.progress = completeCount / totalCount;
                if(this.preloadProgress.progress) {
                    this.preloadLabel.string = (this.preloadProgress.progress * 100).toFixed(0) + '%';
                }

            }, (err, res) => {
                Global.buildRes = res;

                // 加载完成, 开始进入游戏
                this.endPreload();

                if(CC_WECHATGAME) {
                    this._startWxLogin();
                } else {
                    Global.user = {
                        uid: DWTool.getUrlParam('uid'),
                        token: DWTool.getUrlParam('token'),
                        nick: '游客',
                        avatar: "",
                        gender: 1
                    }
        
                    this._getUserInfoAndStartGame();
                }
            });
        });
    },

    loadScene() {
        let dis = 0.012
        this.loginLabel.string = '正在进入好友全明星...'
        this.timeCtrl = () => {
            if (parseInt(this.preloadProgress.progress) == 1) {
                this._preloaded = true;
                this.unschedule(this.timeCtrl);
            } else {
                dis = dis < 0.002 ? 0.002 : dis - 0.0001;
                this.preloadProgress.progress += dis;
            }
            if(!this.preloadRes) {
                this.preloadLabel.string = (this.preloadProgress.progress * 100).toFixed(0) + '%'
            }
        }

        this.schedule(this.timeCtrl, 0.02);
    },

    /**
     * 预加载结束
     */
    endPreload() {
        this.preloadProgress.progress = 1;
    },
    
    _startWxLogin() {
        this.loginLabel.node.active = false;
        this.updateUI.active = false;

        if (Global.needLogin) {
            //服务端通知登录态失效，重新调起微信登录获取新的token
            weChat.login(() => {
                this._getUserInfoAndStartGame();
            });
        } else {
            //检查登录态
            weChat.checkLogin(flag => {
                if (flag) {
                    //登录态未失效，静默登录
                    weChat.loginStatic(() => {
                        this._getUserInfoAndStartGame();
                    })
                } else {
                    //登录态失效，重新调起微信登录获取新的token
                    weChat.login(() => {
                        this._getUserInfoAndStartGame();
                    });
                }
            })
        }
    },

    _getUserInfoAndStartGame() {
        LoginApi.getUserInfoPromise().then(({ data, msg }) => {
            Global.needLogin = false;
            Global.userData = data.userExtra;
            Global.diamond = data.userExtra.diamond;
            Global.skills = data.userSkills;    //拥有技能

            Global.offlineGold = data.offlineGold;  //离线收益

            this.getUserBuildings()
                .then((responseData) => {
                    Global.BuildingManager.networkRooms = responseData.userRooms;
                    cc.director.loadScene("game");
                }).catch((err) => {
                    this._getDataFail();
            });

        }).catch(({ code, msg }) => {
            if (msg) {
                this._getDataFail();
            }
        });
    },

    _getDataFail() {
        this.loginLabel.node.active = false;
        this.updateUI.active = false;
        if (CC_WECHATGAME) {
            weChat.login(() => {
                this._getUserInfoAndStartGame();
        });
        } else {
            console.log();
        }
    },

    getUserBuildings() {
        return new Promise((resolve, reject) => {
            // 获取目标用户的建筑
            HomeApi.getUserBuildings((responseData) => {
                resolve(responseData);
            }, (error) => {
                reject(error);
            });
        })
    },
});