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

cc.Class({
    extends: cc.Component,

    properties: {

        titleNode: cc.Node,

        figureNode: cc.Node,

        backgroundNode: cc.Node,
        infoBackgroundNode: cc.Node,

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

        userInformationNode: cc.Node,  //左边当前人物信息节点
        userAvatar: cc.Sprite,
        userNicknameLabel: cc.RichText,
        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,

        //插卡操作节点
        insertCardNode: cc.Node,
    },

    // 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.backgroundNode.getComponent(cc.Widget).bottom = -500;

            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;
        }
        console.log('node node y '+this.node.y);

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

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

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

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

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

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

        this.insertCardMng = this.insertCardNode.getComponent('UserInsertCard');

        this.figureNode = this.figureNode.getComponent('UserInformationFigure');

        //亲密度显示操作页面
        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( () => {
            GameEvent.fire(GameNotificationKey.VisitFriendHome, this.userInfo.uid);
        }, 1000, true);
    },

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

        this.game = game;
    },

    start() {

    },

    onEnable() {

    },

    setEventListener() {
        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);
            }
        });

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

        GameEvent.on(GameNotificationKey.OpenPack, this, (justOpen) => {
            this.openPack(justOpen);
        });

        GameEvent.on(GameNotificationKey.RefreshInsertCardsInfo, this, (cardInfo,isInsert) => {
            this.refreshCardsInfo(cardInfo,isInsert);
        });

        GameModule.homeGuide.on('Fire_state28', this.trainAction, this);

        GameModule.homeGuide.on('Fire_state31', this.showInseertCard, this);

        GameModule.homeGuide.on('Fire_state25', this.guideShowInteraction, this);

        GameModule.homeGuide.on('Fire_state15', this.changeRelationAction, this);
    },

    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 - 80;
        this.bossButton.node.active = false;

        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 = [];

        this.clearUserData();

        if (this.winSize.height <= 1100) {
            this.node.y = this.winSize.height / 2.0;
        }
    },

    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) {
        this.isRefresh = isRefresh;
        UserInformationApi.getUserInformation(this.uid, (responseData) => {
            // console.log("responseData: " + JSON.stringify(responseData));
            this.loadInformation(responseData);
            if (isRefresh == false) {
                this._userIdArray.push(this.uid);
            }
            this.clearUserData();
        }, (error) => {
            console.log('userinformation error' + error);
            this.bossInformationNode.enabled = true;
        });
    },

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

            //获取到用户信息后再获取动态、插卡信息和抢夺条件
            this.timelineMng.loadUserTimeline(this.uid);
            this.getCardsInfo();
            this.getRelationCondition();
        }
    },

    //获取插卡信息
    getCardsInfo() {
        PackApi.getUserCardsInfo(this.uid, (responseData) => {
            // console.log("responseData: " + JSON.stringify(responseData));
            this.cardsList = responseData.list;
            this.themeMng.configCardsData(responseData.list, this.isRefresh);
        }, (error) => {
            console.log('userinformation error' + error);
            this.cardsList = null;
            this.themeMng.equipCardNode.active = false;
        });
    },

    //获取抢夺条件
    getRelationCondition() {
        var opt = UserInformationRelateOptType.None;
        switch (this.infoRole) {
            case UserInformationType.Boss:
                opt = UserInformationRelateOptType.Redeem;
                break;
            case UserInformationType.OtherArtist:
                opt = UserInformationRelateOptType.Loot;
                break;
            case UserInformationType.ArtistFree:
                opt = UserInformationRelateOptType.Sign;
                break;
            case UserInformationType.MyArtist:
                opt = UserInformationRelateOptType.Fire;
                break;
            default:
                break;
        }
        UserInformationApi.getRelationCondition(this.uid, opt, (responseData) => {
            // console.log("condition: " + JSON.stringify(responseData));
            this.conditionData = responseData;
            this.themeMng.refreshRelationNode();
        }, (error) => {
            console.log('condition error' + error);
            this.conditionData = null;
            this.themeMng.relationButtonNode.active = false;
        });
    },

    //关闭个人信息页
    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;
            if (this.game != undefined) {
                this.game.gameFSM.historyBack();
            }
        }
    },

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

    //清除用户数据
    clearUserData() {
        this.cardsList = [];

        this.conditionData = null;

        this.themeMng.equipCardNode.active = false;
        this.themeMng.relationButtonNode.active = false;
    },
    // update (dt) {},

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

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

            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
                }
            }

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

            if (this.userInfo.nick) {
                this.userNicknameLabel.string = "<img src='"+ genderIcon +"'/> " + this.userInfo.nick;
            }

            var artistName = " 无艺名 ";
            if (this.userInfo.artistName) {
                artistName = " " + this.userInfo.artistName.slice(0,5) + " ";
            }
            var artistString = artistName;
            if (this.infoRole == UserInformationType.MyArtist) {
                let editName = " <img src='artist_name_edit' click='clickEditName'/>";
                artistString += editName;
            }
            this.artistNameText.string = artistString;

            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 = 'user_female';
            if (this.bossInfo.gender == 1) {
                genderIcon = 'user_male';
            }

            var artistName = " 无艺名";
            if (this.bossInfo.artistName) {
                artistName = " " + this.bossInfo.artistName.slice(0,4);
            }
            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 - 80;

        let hasBoss = this.bossInfo ? true : false;
        let hasJob = this.userInfo.jobId != UserJobType.None;

        this.themeMng.changeTheme(this.infoRole, hasBoss, hasJob);

        this.figureNode.changeFigure(this.userInfo);

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

    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, 152, 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, -152, 0);
            this.bossButton.node.runAction(buttonAction);
        }
    },

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

    //抢夺、赎身、签约操作
    changeRelationAction() {

        if (!this.conditionData) {
            return;
        }

        this.themeMng.relationButtonNode.enabled = false;

        var opt = UserInformationRelateOptType.None;
        switch (this.infoRole) {
            case UserInformationType.Boss:
                opt = UserInformationRelateOptType.Redeem;
                break;
            case UserInformationType.OtherArtist:
                opt = UserInformationRelateOptType.Loot;
                break;
            case UserInformationType.ArtistFree:
                opt = UserInformationRelateOptType.Sign;
                break;
            case UserInformationType.MyArtist:
                opt = UserInformationRelateOptType.Fire;
                break;
            default:
                break;
        }

        let string = tipsInfo.changeRelationTitle[opt].content;

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

        //其他人艺人或自由身显示才引导
        if (this.infoRole == UserInformationType.OtherArtist || this.infoRole == UserInformationType.ArtistFree ) {
            this.scheduleOnce(function() {
                GameModule.homeGuide.getComponent('HomeGuide').handleGuideStateNext('state15', 'state16');
            }, 0.1);
        }
    },

    confirmChangeRelation(opt) {
        this.changeRelate(opt);
        this.changeRelationNode.active = false;
    },

    /**
     * 修改用户状态
     * @param {UserInformationRelateOptType} type
     */
    changeRelate(opt) {
        UserInformationApi.postRelate(this.uid, opt, (responseData) => {
            // console.log("responseData: " + JSON.stringify(responseData));
            var bossUid = 0;
            switch (opt) {
                case UserInformationRelateOptType.Loot:
                    bossUid = this.bossInfo.uid;
                    break;
                default:
                    break;
            }
            this.themeMng.showChangeRelationSuccess(tipsInfo.relationSuccess[opt].image);
            if (bossUid > 0) {
                GameEvent.fire(GameNotificationKey.NoticeRoleOpt, this.uid, opt, bossUid);
            } else {
                GameEvent.fire(GameNotificationKey.NoticeRoleOpt, this.uid, opt);
            }

            GameModule.userInfo.grossIncome -= this.conditionData.coin;
            this.themeMng.relationButtonNode.enabled = true;
            this.isRefresh = true;
            this.loadInformation(responseData);
            GameEvent.fire(GameNotificationKey.RefreshFriendList);
        }, (code, msg) => {
            var errorString = msg;
            if (code == 805) {
                errorString = tipsInfo.relationFail805[opt].content;
            }
            let errorImage = tipsInfo.relationFail[opt].image;
            this.errorMng.showRelationErrorAlert(errorImage, 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.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.infoRole == UserInformationType.MyArtist) {
            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);
    },

    guideShowInteraction() {
        this.scheduleOnce(function() {
            this.interaction.showInteraction(UserInteractionType.Pacify);
        }, 0.1);
    },

    //突破按钮点击，职业进阶
    levelUpgradeAction() {
        if (this.userInfo) {
            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) {
                GameEvent.fire(GameNotificationKey.ShowJobPage, JobPageType.ChooseJob, this.userInfo, this.node.zIndex);
            } else {
                GameEvent.fire(GameNotificationKey.ShowJobPage, JobPageType.ChangeJob, this.userInfo, this.node.zIndex);
            }
        }
    },

    //打开背包
    openPackAction() {
        GameEvent.fire(GameNotificationKey.OpenPack,true);
    },

    openPack(justOpen) {
        this.pack.init(justOpen,this.uid);
        this.pack.showPack();
    },

    //打开插卡页面
    showInseertCard() {
        this.insertCardNode.active = true;
        this.insertCardMng.init(this.cardsList, this.uid);
    },

    refreshCardsInfo(cardInfo,isInsert) {
        if (isInsert) {
            if (this.cardsList != undefined) {
                this.cardsList.push(cardInfo);
            } else {
                this.cardsList = [];
                this.cardsList.push(cardInfo);
            }
        } else {
            for(var index in this.cardsList) {
                let item = this.cardsList[index];
                if (item.id == cardInfo.id) {
                    this.cardsList.splice(index,1);
                    break;
                }
            }
        }
        this.themeMng.configCardsData(this.cardsList);
    }
});
