var Api = require('../net/Api');
var UserInformationApi = require('../net/UserInformationApi');
var { UserInformationType, UserInformationRelateOptType, GameNotificationKey, UserInteractionType, JobPageType, UserJobType} = require('../utils/GameEnum');
var DWTool = require('../utils/DWTool');
const AlertManager = require('../utils/AlertManager');

cc.Class({
    extends: cc.Component,

    properties: {

        titleNode: cc.Node,

        infoBackgroundNode: cc.Node,

        informationNode: cc.Node,   //用户信息节点

        userInformationNode: cc.Node,  //左边当前人物信息节点
        userAvatar: cc.Sprite,
        userNicknameLabel: cc.Label,

        artistNameText: cc.RichText,

        bossButton: cc.Button,  //显示老板按钮

        bossInformationNode: cc.Node,
        bossAvatar: cc.Sprite,
        bossNicknameLabel: cc.Label,
        bossArtistNameText: cc.RichText,

        timelineNode: cc.Node,  //动态节点

        //用户角色
        infoRole: {
            default:UserInformationType.Mine,
            visible: false,
        },

        //关系改变弹窗：抢夺、赎身、签约
        changeRelationNode: cc.Node,

        //修改艺名节点
        editNameNode: cc.Node,
        editboxName: cc.EditBox,

        //提示框节点
        errorNode: cc.Node,

        _userIdArray: [cc.Integer],

        themeNode: cc.Node,

        jobNode: cc.Node,

        //个人属性节点
        propertyNode: cc.Node,

        //互动、亲密度相关操作
        interactionPrefab: cc.Prefab,

        //背包预制
        packPrefab: cc.Prefab,
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad() {
        this.bossInformationNode.on('touchend', this.showBossInfoToView, this);

        this.editNameNode.on('touchend', this.closeEditName, this);

        this.jobNode.on('touchend', this.changeJob, this);

        let XHeight = 1624;
        this.winSize = cc.view.getVisibleSize();

        let nodeY = this.winSize.height / 2.0;
        this.node.y = nodeY;

        this.infoTop = 135;
        if (this.winSize.height >= XHeight) {
            this.titleNode.getComponent(cc.Widget).top = 80;
            this.infoBackgroundNode.getComponent(cc.Widget).top = -50;
            this.informationNode.getComponent(cc.Widget).top = 185;
            this.infoTop = 185;
        }

        let timelineHeight = (this.winSize.height - this.infoTop - this.informationNode.height);
        this.timelineNode.height = timelineHeight;
        this.timelineNode.y = timelineHeight - this.winSize.height;

        //适配pad尺寸修改
        if (this.winSize.height <= 1100) {
            this.scrollY = 0;

            this.node.setContentSize(cc.size(this.winSize.width, 1334));
            let maxHeight = 1334 - nodeY;

            this.node.on(cc.Node.EventType.TOUCH_START, function (event) {
                this.scrollY = event.getLocation().y;
            }, this);

            this.node.on(cc.Node.EventType.TOUCH_MOVE, function (event) {
                let moveY = event.getLocation().y;
                if (moveY <= this.scrollY) {
                    if (this.node.y <= nodeY) {
                        this.node.y = nodeY;
                    } else {
                        this.node.y -= Math.min((this.scrollY - moveY), 20);
                    }
                } else {
                    if (this.node.y >= maxHeight) {
                        this.node.y = maxHeight;
                    } else {
                        this.node.y += Math.min((moveY - this.scrollY), 20);
                    }
                }
                this.scrollY = moveY;
            }, this);

            let timelineHeight = (1334 - this.infoTop - this.informationNode.height);
            this.timelineNode.height = timelineHeight;
            this.timelineNode.y = timelineHeight - 1334;
        }

        this.artistNameText.getComponent('UserInformationRichText').init(this);

        this.errorMng = this.errorNode.getComponent('UserInformationAlert');
        this.errorMng.init(this);

        this.timelineMng = this.timelineNode.getComponent('UserInformationTimeline');
        this.timelineMng.init();

        this.relationAlertMng = this.changeRelationNode.getComponent('UserInformationAlert');
        this.relationAlertMng.init(this);

        this.themeMng = this.themeNode.getComponent('UserInformationTheme');
        this.themeMng.init(this);

        this.propertyMng = this.propertyNode.getComponent('UserInformationProperty');
        this.propertyMng.init(this);

        //亲密度显示操作页面
        this.interaction = cc.instantiate(this.interactionPrefab);
        this.interaction = this.interaction.getComponent('UserInteraction');

        //背包页面
        //亲密度显示操作页面
        this.pack = cc.instantiate(this.packPrefab);
        this.pack = this.pack.getComponent('UserPack');

        this.setEventListener();

        this.trainEvent = _.debounce(() => {

            //0为还没选择职业将不能进行培养，跳去选择职业界面
            if (this.userInfo.jobId == UserJobType.None) {
                
                AlertManager.showArtistTrainNoJob(() => {
                    this.changeJob();
                }, this.node.zIndex);

            } else {
                AlertManager.showTrainAlert(this.userInfo.uid, this.node.zIndex);
            }
            
        }, 1000, true);

        this.visitEvent = _.debounce( () => {
            Global.GameEvent.fire(GameNotificationKey.VisitFriendHome, this.userInfo.uid);
        }, 1000, true);
    },

    init(uid) {
        this.node.parent = cc.find("Canvas");
        this.node.setContentSize(cc.view.getVisibleSize());
        this.node.active = true;
        this.node.zIndex += 1;
        this.loadUserInformation(uid);
    },

    start() {

    },

    onEnable() {

    },

    setEventListener() {
        Global.GameEvent.on(GameNotificationKey.ShowInteraction, this, () => {
            if (this.responseData.interactionInfo) {
                var isCommon = (this.infoRole == UserInformationType.Boss || this.infoRole == UserInformationType.MyArtist) ? false : true;
                this.interaction.showIntimacyInfo(isCommon);
            }
        });

        Global.GameEvent.on(GameNotificationKey.RefreshUserInformation, this, () => {
            this.getNetworkData(true);
        });
    },

    onDisable() {
        this.bossInformationNode.enabled = true;
        this.bossInformationNode.active = false;
        this.bossInformationNode.x = this.winSize.width / 2.0;
        this.bossButton.node.x = this.winSize.width / 2.0 - 84;

        this.themeMng.relationButtonNode.enabled = true;
        this.themeMng.successNode.active = false;
        this.editNameNode.active = false;
        this.changeRelationNode.active = false;
        this.errorNode.active = false;

        this.node.zIndex = 0;
        this._userIdArray = [];
    },

    loadUserInformation(uid) {
        if (uid) {
            this.uid = uid;
        }
        if (Global.user.uid == this.uid) {
            this.isSelf = true;
        } else {
            this.isSelf = false;
        }
        this.getNetworkData(false);
    },

    //获取个人信息
    getNetworkData(isRefresh) {
        UserInformationApi.getUserInformation(this.uid, (responseData) => {
            // console.log("responseData: " + JSON.stringify(responseData));
            this.loadInformation(responseData);
            if (isRefresh == false) {
                this._userIdArray.push(this.uid);
            }
        }, (error) => {
            console.log('userinformation error' + error);
            this.bossInformationNode.enabled = true;
        });
    },

    loadInformation(responseData) {
        if (responseData) {
            this.role = responseData.role;
            this.currentUserCost = responseData.currentUserCost;
            this.userInfo = responseData.userInfo;
            this.bossInfo = responseData.bossInfo;
            this.responseData = responseData;
            this.refreshThemeUI();

            this.timelineMng.loadUserTimeline(this.uid);
        }
    },

    //关闭个人信息页
    closeInformationAction() {
        if (this._userIdArray.length > 1) {
            let uid = this._userIdArray[this._userIdArray.length - 2];
            this.loadUserInformation(uid);
            this.removeItems(this._userIdArray, 2);
        } else {
            this.node.active = false;
        }
    },

    removeItems(arr, item) {
        for (var i = 0; i < item; i++) {
            arr.pop();
        }
    },
    // update (dt) {},

    //根据不同用户状态信息显示
    refreshThemeUI() {
        if (this.userInfo) {

            if (this.userInfo.head) {
                Api.createImageFromUrl(this.userInfo.head, (spriteFrame) => {
                    this.userAvatar.spriteFrame = spriteFrame;
                });
            }

            if (this.userInfo.nick) {
                this.userNicknameLabel.string = this.userInfo.nick;
            }

            var genderIcon = 'artist_female';
            if (this.userInfo.gender == 1) {
                genderIcon = 'artist_male';
            }
            var artistName = " 无艺名 ";
            if (this.userInfo.artistName) {
                artistName = " " + this.userInfo.artistName.slice(0,5) + " ";
            }
            var artistString = "<img src='"+ genderIcon +"'/><outline color=white width=2> " + artistName + "</outline>";
            if (this.role == 2) {
                let editName = "<img src='artist_name_edit' click='clickEditName'/>";
                artistString += editName;
            }

            this.artistNameText.string = artistString;

            if (this.isSelf) {
                this.infoRole = UserInformationType.Mine;
            } else {
                switch (this.role) {
                    case UserInformationType.Boss:
                        this.infoRole = UserInformationType.Boss;
                        break;
                    case UserInformationType.MyArtist:
                        this.infoRole = UserInformationType.MyArtist;
                        if (this.userInfo.artistName) {
                            this.editNameNode.string = this.userInfo.artistName;
                        }
                        break;
                    case UserInformationType.ArtistFree:
                        this.infoRole = UserInformationType.ArtistFree;
                        break;
                    case UserInformationType.OtherArtist:
                        this.infoRole = UserInformationType.OtherArtist;
                        break;
                    default:
                        break
                }
            }

            this.propertyMng.setUserData(this.userInfo, this.infoRole);
        }

        if (this.bossInfo) {
            this.bossButton.node.active = true;

            if (this.bossInfo.head) {
                Api.createImageFromUrl(this.bossInfo.head, (spriteFrame) => {
                    this.bossAvatar.spriteFrame = spriteFrame;
                });
            }

            if (this.bossInfo.nick) {
                this.bossNicknameLabel.string = this.bossInfo.nick;
            }

            var genderIcon = 'artist_female';
            if (this.userInfo.gender == 1) {
                genderIcon = 'artist_male';
            }

            var artistName = " 无艺名";
            if (this.bossInfo.artistName) {
                artistName = " " + this.bossInfo.artistName.slice(0,3);
            }
            var artistString = "<img src='"+ genderIcon +"'/><outline color=white width=2> " + artistName + "</outline>";
            this.bossArtistNameText.string = artistString;
        } else {
            this.bossButton.node.active = false;
        }
        this.bossInformationNode.enabled = true;
        this.bossInformationNode.active = false;
        this.bossInformationNode.x = this.winSize.width / 2.0;
        this.bossButton.node.x = this.winSize.width / 2.0 - 84;

        if (this.responseData.interactionInfo) {
            this.interaction.init(this.uid, this.responseData.interactionInfo, this);
            this.configIntimacy(this.responseData.interactionInfo);
        }

        this.themeMng.changeTheme(this.infoRole);
    },

    showBossInfo() {
        if (this.bossInformationNode.active === true) {
            let callBack = cc.callFunc(function () {
                this.bossInformationNode.active = false;
            }, this);
            let positionAction = cc.moveBy(0.15, 153, 0);
            this.bossInformationNode.runAction(cc.sequence(positionAction, callBack));

            let buttonAction = cc.moveBy(0.15, 148, 0);
            this.bossButton.node.runAction(buttonAction);
        } else {
            this.bossInformationNode.active = true;

            let positionAction = cc.moveBy(0.15, -153, 0);
            this.bossInformationNode.runAction(positionAction);

            let buttonAction = cc.moveBy(0.15, -148, 0);
            this.bossButton.node.runAction(buttonAction);
        }
    },

    showBossInfoToView() {
        this.bossInformationNode.enabled = false;
        this.loadUserInformation(this.bossInfo.uid);
    },

    //抢夺、赎身、签约操作
    changeRelationAction() {
        this.themeMng.relationButtonNode.enabled = false;

        var string = '';
        var coinString = '';
        switch (this.infoRole) {
            case UserInformationType.Boss:
                string = "赎身需要付出<color=#f73939>两倍</c>的签约费\n你确定要赎身吗？";
                coinString = (this.currentUserCost * 2).toString();
                break;
            case UserInformationType.OtherArtist:
                string = '是否签约该好友成为旗下艺人？\n签约该好友需要消耗：';
                coinString = (this.userInfo.cost).toString();
                break;
            case UserInformationType.ArtistFree:
                string = '是否签约该好友成为旗下艺人？\n签约该好友需要消耗：';
                coinString = (this.userInfo.cost).toString();
                break;
            default:
                break;
        }

        this.relationAlertMng.showRelationAlert(string, coinString, () => {
            this.changeRelationNode.active = false;
        }, () => {
            this.confirmChangeRelation();
        });
    },

    confirmChangeRelation() {
        switch (this.infoRole) {
            case UserInformationType.Boss:
                this.changeRelate(UserInformationRelateOptType.Redeem);
                break;
            case UserInformationType.OtherArtist:
                this.changeRelate(UserInformationRelateOptType.Loot);
                break;
            case UserInformationType.ArtistFree:
                this.changeRelate(UserInformationRelateOptType.Sign);
                break;
            default:
                break;
        }
        this.changeRelationNode.active = false;
    },

    /**
     * 修改用户状态
     * @param {UserInformationRelateOptType} type
     */
    changeRelate(type) {
        UserInformationApi.postRelate(this.uid, type, (responseData) => {
            console.log("responseData: " + JSON.stringify(responseData));
            switch (type) {
                case UserInformationRelateOptType.Redeem:
                    this.themeMng.showChangeRelationSuccess('userInformation/userinformation_redeem_success');
                    break;
                case UserInformationRelateOptType.Loot:
                    this.themeMng.showChangeRelationSuccess('userInformation/userinformation_loot_success');
                    break;
                case UserInformationRelateOptType.Sign:
                    this.themeMng.showChangeRelationSuccess('userInformation/userinformation_sign_success');
                    break;
                default:
                    break;
            }
            this.themeMng.relationButtonNode.enabled = true;
            this.loadInformation(responseData);
            Global.GameEvent.fire(GameNotificationKey.RefreshFriendList);
        }, (code, msg) => {
            var errorString = msg;
            var errorImageUrl = '';
            switch (type) {
                case UserInformationRelateOptType.Redeem:
                    if (code == 805) {
                        errorString = "<color=#f73939>金币不足</c>，赚到更多的金币\n再来赎身吧~";
                    }
                    errorImageUrl = 'userInformation/userinformation_redeem_fail';
                    break;
                case UserInformationRelateOptType.Loot:
                    if (code == 805) {
                        errorString = "<color=#f73939>金币不足</c>，赚到更多的金币\n再来抢夺吧~";
                    }
                    errorImageUrl = 'userInformation/userinformation_loot_fail';
                    break;
                case UserInformationRelateOptType.Sign:
                    if (code == 805) {
                        errorString = "<color=#f73939>金币不足</c>，赚到更多的金币\n再来抢约吧~";
                    }
                    errorImageUrl = 'userInformation/userinformation_sign_fail';
                    break;
                default:
                    break;
            }

            this.errorMng.showRelationErrorAlert(errorImageUrl, errorString, () => {

            });

            this.themeMng.relationButtonNode.enabled = true;
        });
    },

    //修改艺人名字
    showEditName() {
        this.editNameNode.active = true;
        if (this.userInfo.artistName) {
            this.editboxName.string = this.userInfo.artistName;
        }
        this.editboxName.setFocus(true);
    },

    confirmEditName() {
        UserInformationApi.editArtistName(this.uid, this.editboxName.string, (responseData) => {
            console.log("修改艺名成功 " + JSON.stringify(responseData));
            this.reloadArtistName();
            this.closeEditName();
        }, (error) => {
            console.log('修改艺名失败' + error);
            // this.alertMng.showAlert('修改艺名失败','',this.infoRole);
        });
        this.editNameNode.active = false;
    },

    reloadArtistName() {
        this.userInfo.artistName = this.editboxName.string;

        var genderIcon = 'artist_female';
        if (this.userInfo.gender == 1) {
            genderIcon = 'artist_male';
        }

        var artistName = " 无艺名 ";
        if (this.userInfo.artistName) {
            artistName = " " + this.userInfo.artistName.slice(0,5) + " ";
        }

        var artistString = "<img src='"+ genderIcon +"'/><outline color=white width=2> " + artistName + "</outline>";
        if (this.role == 2) {
            let editName = "<img src='artist_name_edit' click='clickEditName'/>";
            artistString += editName;
        }

        this.artistNameText.string = artistString;
    },

    closeEditName() {
        this.editboxName.setFocus(false);
        if (window.wx != undefined) {
            wx.hideKeyboard();
        }
        this.editNameNode.active = false;
    },

    //跳转到指定用户家园
    showUserHome() {
        this.node.active = false;
        this.visitEvent();
    },

    //培养按钮点击
    trainAction() {
        this.trainEvent();
    },

    //亲密度数据设置
    configIntimacy(interactionInfo) {
        this.themeMng.configIntimacyData(interactionInfo);
    },

    showInteraction(event,customEventData) {
        //判断互动是否正向
        var isGood = false;
        if (customEventData == 'true') {
            isGood = true;
        }

        var interactionType = UserInteractionType.Common;
        switch (this.infoRole) {
            case UserInformationType.Boss:
                interactionType = isGood ? UserInteractionType.PlayUp : UserInteractionType.Revolt;
                break;
            case UserInformationType.MyArtist:
                interactionType = isGood ? UserInteractionType.Pacify : UserInteractionType.Order;
                break;
            default:
                break;
        }
        this.interaction.showInteraction(interactionType);
    },

    //突破按钮点击，职业进阶
    levelUpgradeAction() {
        if (this.userInfo) {
            Global.GameEvent.fire(GameNotificationKey.ShowJobPage, JobPageType.LevelUp, this.userInfo, this.node.zIndex);
        }
    },

    //选择或转换职业
    changeJob() {
        if (this.infoRole == UserInformationType.MyArtist && this.userInfo) {
            //0为还没有选择职业，其他为已选择职业转职
            if (this.userInfo.jobId == UserJobType.None) {
                Global.GameEvent.fire(GameNotificationKey.ShowJobPage, JobPageType.ChooseJob, this.userInfo, this.node.zIndex);
            } else {
                Global.GameEvent.fire(GameNotificationKey.ShowJobPage, JobPageType.ChangeJob, this.userInfo, this.node.zIndex);
                // this.levelUpgradeAction();
            }
        }
    },

    //打开背包
    openPack() {
        this.pack.init();
        this.pack.showPack();
    }
});
