
var GameModule = require("./utils/GameModule");
const FriendSystemApi = require('./net/FriendSystemApi');
const ShareAction = require('./utils/ShareAction');
var DWTool = require('./utils/DWTool');
var HomeApi = require("./net/HomeApi");
const JobApi = require('./net/JobApi');
const { GameNotificationKey, SenceMap, JobPageType} = require('./utils/GameEnum');
const AlertManager = require('./utils/AlertManager');

cc.Class({
    extends: cc.Component,

    properties: {

        levelHomePrefab: cc.Prefab,

        wechatFriendNode: cc.Node,

        //用户信息页
        userInfoPrefab: cc.Prefab,

        myInfoTop: cc.Node,

        myTabBottom: cc.Node,

        friendInfoTop: cc.Node,

        friendTabBottom: cc.Node,

        _otherActor: cc.Node,

        friendSystemPrefab: cc.Prefab,

        friendHeadSprite: cc.Sprite,

        jobChangePrefab: cc.Prefab,

        talentPagePrefab: cc.Prefab,

        _isEnterFriendHome: false,

        chooseJob: cc.Node,
    },


    onLoad() {

        GameModule.game = this.node;
        this.senceHistory = [];
        this.buyTipNode = null;

        //我的家园
        let levelHome = cc.instantiate(this.levelHomePrefab);
        levelHome = levelHome.getComponent('LevelHome')
        levelHome.init(Global.user.uid, 1, true);
        this.levelHome = levelHome;

        //用户信息面板
        this.userInfo = cc.instantiate(this.userInfoPrefab);
        this.userInfo = this.userInfo.getComponent('UserInformation');

        //好友系统Tab面板
        let friendSystem = cc.instantiate(this.friendSystemPrefab);
        this.friendSystemScript = friendSystem.getComponent('FriendSystem');

        //好友家园
        let friendHome = cc.instantiate(this.levelHomePrefab);
        friendHome = friendHome.getComponent('LevelHome')
        this.friendHome = friendHome;

        //突破界面
        let breakOut = "";
        this.breakOut = breakOut;

        // //转职界面
        // this.jobChange = cc.instantiate(this.jobChangePrefab);
        // this.jobChange = this.jobChange.getComponent('ChangeJob');

        //星探界面
        this.finder = cc.instantiate(this.talentPagePrefab);
        this.finder = this.finder.getComponent('TalentPage');

        // 监听事件
        this.setEventListener();

        this.enterLevelHome();

        if (Global.shareUid != -1) {
            console.log('shareUid: ' + Global.shareUid);
            this.processShareAction();
        }

        this.friendHeadSprite.node.on(cc.Node.EventType.TOUCH_END, () => {
            Global.GameEvent.fire(GameNotificationKey.ShowUserInfomation, this.friendHome.uid);
        }, this);
    },

    /**
     * 进入好友家园
     * @param {Number} uid 用户id
     */
    enterFriendHome(uid) {
        this.friendHome.initFriend(uid, 1, res => {

            if (this._isEnterFriendHome) { return; }
            this._isEnterFriendHome = true;

            let actionTop = cc.moveBy(0.4, cc.v2(0, -this.friendInfoTop.height));
            this.friendInfoTop.runAction(actionTop);

            let actionRight = cc.moveBy(0.4, cc.v2(-270, 0));
            this.friendTabBottom.runAction(actionRight);

            this.friendHome.node.active = true;
        })
    },

    /**
     * 离开好友家园
     * @param {Number} uid 用户id
     */
    outFriendHome(uid) {

        this._isEnterFriendHome = false;
        let actionTop = cc.moveBy(0.4, cc.v2(0, this.friendInfoTop.height));
        this.friendInfoTop.runAction(actionTop);

        let actionRight = cc.moveBy(0.4, cc.v2(270, 0));
        this.friendTabBottom.runAction(actionRight);

        this.friendHome.node.active = false;
    },

    /**
     * 进入我的家园
     */
    enterLevelHome() {
        let actionTop = cc.moveBy(0.4, cc.v2(0, -this.myInfoTop.height));
        this.myInfoTop.runAction(actionTop);

        if (!this.isFirstLoad) {
            this.isFirstLoad = true;
            let actionBottom = cc.moveBy(0.4, cc.v2(0, this.myTabBottom.height + 6));
            this.myTabBottom.runAction(actionBottom);
        }

        this.levelHome.node.active = true;

        this.refreshActorNoJob();
    },

    /**
     * 离开我的家园
     */
    outLevelHome() {

        if (this._isEnterFriendHome) { return; }

        let actionTop = cc.moveBy(0.4, cc.v2(0, this.myInfoTop.height));
        this.myInfoTop.runAction(actionTop);
    },

    enterUserInfo() {
        this.userInfo.init(uid);
    },

    enterSence(senceName) {
        switch (senceName) {
            case SenceMap.LevelHome:
                //进入我的家园

                break;
            case SenceMap.UserPanel:
                //进入用户信息面板
                this.enterUserInfo();
                break;
            case SenceMap.FriendSystem:
                //进入好友Tab面板

                break;
            case SenceMap.FriendHome:
                //进入好友家园

                break;
            case SenceMap.BreakOut:
                //进入突破界面

                break;
            case SenceMap.Finder:
                //进入星探界面

                break;
            default:
                break;
        }
        //历史记录
        if (this.senceHistory[this.senceHistory.length - 1] != senceName) {
            this.senceHistory.push(senceName)
        }
    },

    senceBack() {
        this.senceHistory.pop()
        let lastSence = this.senceHistory[this.senceHistory.length - 1]
        this.enterSence(lastSence)
    },

    /**
     * 查看他人艺人列表
     */
    showOtherActors() {
        DWTool.loadResPrefab('./prefabs/other_actor')
            .then((result) => {
                this._otherActor = cc.instantiate(result);
                this._otherActor.getComponent("OtherActor").uid = this.friendHome.uid;
                this._otherActor.parent = cc.find("Canvas");
            }).catch((err) => {
                cc.error(err);
            });
    },

    /**
     * 关闭他人艺人列表
     */
    closeOtherActors() {
        this._otherActor.destroy();
    },

    showFriendSystem() {
        this.friendSystemScript.show(this.wechatFriendNode);
    },

    closeFriendSystem() {
        this.friendSystemScript.close();
    },


    // showJobChange() {
    //     this.jobChange.show(JobPageType.ChangeJob);
    // },


    // showJobChoose() {
    //     this.jobChange.show(JobPageType.ChooseJob);
    // },


    // showJobLevelUp() {
    //     this.jobChange.show(JobPageType.LevelUp);
    // },


    //转职
    //选择职业
    //职业突破页面
    showJobPage(type, userInfo, zIndex) {

        let self = this;

        cc.loader.loadRes('/prefabs/change_job', cc.Prefab, (error, prefab) => {
            if (error === null) {
                let jobChange = cc.instantiate(prefab);
                this.jobChange = jobChange.getComponent('ChangeJob');
                this.jobChange.show(type, userInfo, zIndex);
            } else {
                console.log(JSON.stringify(error));
            }
        });
    },

    showChooseJob() {
        let self = this;
        cc.loader.loadRes('/prefabs/change_job', cc.Prefab, (error, prefab) => {
            if (error === null) {
                let jobChange = cc.instantiate(prefab);
                this.jobChange = jobChange.getComponent('ChangeJob');
                this.jobChange.showFromTalent(JobPageType.ChooseJob, self.noJobActors);
            } else {
                console.log(JSON.stringify(error));
            }
        });
    },

    //关闭转职，选择职业，突破页面
    closeJobPage() {
        this.jobChange.close();
    },

    showTalentPage() {
        this.finder.show();
    },

    showNoticePopup() {
        AlertManager.showNoticePopup();
    },

    // 监听事件
    setEventListener() {

        Global.GameEvent.on(GameNotificationKey.ShowFriendSystem, this, () => {
            this.showFriendSystem();
        });

        Global.GameEvent.on(GameNotificationKey.VisitFriendHome, this, (uid) => {
            if (uid) {
                this.closeFriendSystem();
                this.outLevelHome();
                this.enterFriendHome(uid)
            }
            // setTimeout(function () {
            //     let otherHome = cc.instantiate(this.homePrefab);
            //     otherHome.getComponent('Home').init(user.uid, 1, false);
            //     otherHome.getComponent('Home').configUserInfo(user);
            //     otherHome.zIndex = 1;
            //     otherHome.parent = this.node;
            // }.bind(this), 800);

        });

        Global.GameEvent.on(GameNotificationKey.BackOwnerHome, this, (otherHomeNode) => {

            setTimeout(function () {
                otherHomeNode.destroy()
            }.bind(this), 1000);
        });

        Global.GameEvent.on(GameNotificationKey.ShowUserInfomation, this, (uid) => {
            this.userInfo.init(uid);
        });


        Global.GameEvent.on(GameNotificationKey.ProcessShareAction, this, this.processShareAction);

        Global.GameEvent.on(GameNotificationKey.ShowJobPage, this, this.showJobPage);

        Global.GameEvent.on(GameNotificationKey.ShowJobPageFromTalent, this, this.showChooseJob);

        Global.GameEvent.on(GameNotificationKey.RefreshFriendList, this, this.refreshActorNoJob);
    },

    onDestroy() {

        Global.GameEvent.off(GameNotificationKey.ShowFriendSystem, this);
        Global.GameEvent.off(GameNotificationKey.VisitFriendHome, this);
        Global.GameEvent.off(GameNotificationKey.BackOwnerHome, this);
        Global.GameEvent.off(GameNotificationKey.ProcessShareAction, this);
        Global.GameEvent.off(GameNotificationKey.ShowUserInfomation, this);
        Global.GameEvent.off(GameNotificationKey.ShowJobChoose, this);
        Global.GameEvent.off(GameNotificationKey.ShowJobPage, this);
        Global.GameEvent.off(GameNotificationKey.RefreshFriendList, this);
        Global.GameEvent.off(GameNotificationKey.ShowJobPageFromTalent, this);
    },

    processShareAction() {
        console.log('processShareAction');
        if (Global.user != null) {
            if (Global.shareType == ShareAction.ADD_FRIEND) {
                FriendSystemApi.addFriend(Global.shareUid, () => {
                    Global.GameEvent.fire('refresh_friend_list');
                });
            }
            Global.shareUid = -1;
            Global.shareType = ShareAction.None;
        }
    },

    refreshActorNoJob() {
        JobApi.actorsNoJob(
            (response) => {
                if (response.list && !_.isEmpty(response.list) && response.list.length > 0) {
                    this.chooseJob.active = true;
                    this.noJobActors = response.list;
                } else {
                    this.chooseJob.active = false;
                }
            },
            (code, msg) => {
                // this.chooseJob.active = false;
            }
        );
    },

});
