const DWTool = require("../utils/DWTool");
const { ArtistOperation, GameNotificationKey } = require("../utils/GameEnum");
const Api = require('../net/Api');
const HomeApi = require("../net/HomeApi");
const GameModule = require("../utils/GameModule");
const AlertManaget = require("../utils/AlertManager");

cc.Class({
    extends: cc.Component,

    properties: {

        titleRichText: cc.RichText,

        headSprite: cc.Sprite,

        nickRichText: cc.RichText,

        levelLabel: cc.Label,

        jobTitleLabel: cc.Label,

        gainDetailLabel: cc.Label,

        gainCoinLabel: cc.Label,

        recallArtistTipLabel: cc.Label,

        recallArtistFailTipRichText: cc.RichText,
        
        reportArtistTipLabel: cc.Label,

        reportArtistFailTipRichText: cc.RichText,

        driveAwayFailTipRichText: cc.RichText,

        gellAllCoinBtn: cc.Button,

        confrimBtn: cc.Button,

        coinNode: cc.Node,

        content: cc.Node,

        coinPrefab: cc.Prefab,

        benefit: {
            get: function() {
                if (!this._benefit) {
                    this._benefit = 0;
                }
                return this._benefit;
            },
            set: function (value) {
                this._benefit = value;
                this.gainCoinLabel.string = DWTool.coinParse(this._benefit);
            }
        }
    },

    init(buildingInfo, uid, isSelf, artistData) {

        this.isSelf = isSelf;
        this.artistData = artistData;
        this.buildingInfo = buildingInfo;
        this.uid = uid;
        this.getNetworkData();
    },

    getNetworkData() {
        
        HomeApi.friendGetBenefit(this.artistData.id || this.artistData.uid, (data) => {

            let time = (Date.parse(new Date()) - data.stationTime) / 1000;
            this.gainDetailLabel.string = `演出时长: ${DWTool.calculateTime(time)}` 

            if (data.role === 2) {
                // if (time < 900) { // 入驻15分钟才可以召回
                //     this.setStyleByOperation(ArtistOperation.RecalArtistlFail);
                // } else {
                //     this.setStyleByOperation(ArtistOperation.RecallArtist);    
                // }
                this.setStyleByOperation(ArtistOperation.RecallArtist);   
            } else {
                if (this.isSelf) {
                    // if (time < 900) { // 入驻15分钟才可以驱赶
                    //     this.setStyleByOperation(ArtistOperation.DriveAwayArtistFail);
                    // } else {
                    //     this.setStyleByOperation(ArtistOperation.DriveAwayArtist);
                    // }
                    this.setStyleByOperation(ArtistOperation.DriveAwayArtist);
                } else {

                    if (data.isReported) { // 是否举报过；0:否;1:是
                        this.setStyleByOperation(ArtistOperation.ReportArtistFail);
                    } else {
                        this.setStyleByOperation(ArtistOperation.ReportArtistSuccess);  
                    }
                }
            }

            this.operationData = data;
            this.jobTitleLabel.string = data.jobName;
            this.levelLabel.string = data.jobLevel;
            this.nickRichText.string = `<color=#584a47>${data.nick}</c> <img src='${data.picId}'/>`;
            this.benefit = data.benefit;
            
            Api.createImageFromUrl(data.head, (spriteFrame) => {
                this.headSprite.spriteFrame = spriteFrame;
            }, null);

        }, (code, msg) => {
            console.log(msg);
        });
    },

    setStyleByOperation(operation) {
        if (this.operation === operation) {
            return;
        }

        switch (operation) {
            case ArtistOperation.RecallArtist:
                this.setTitleString("艺人召回");
                this.recallArtistTipLabel.node.active = true;
                this.recallArtistFailTipRichText.node.active = false;
                this.reportArtistTipLabel.node.active = false;
                this.reportArtistFailTipRichText.node.active = false;
                this.gellAllCoinBtn.node.active = false;
                this.confrimBtn.node.active = true;
                this.driveAwayFailTipRichText.node.active = false;
                break;

            case ArtistOperation.RecalArtistlFail:
                this.setTitleString("艺人召回");
                this.recallArtistTipLabel.node.active = false;
                this.recallArtistFailTipRichText.node.active = true;
                this.reportArtistTipLabel.node.active = false;
                this.reportArtistFailTipRichText.node.active = false;
                this.gellAllCoinBtn.node.active = false;
                this.confrimBtn.node.active = true;
                this.driveAwayFailTipRichText.node.active = false;
                break;

            case ArtistOperation.ReportArtistSuccess:
                this.setTitleString("举报艺人");
                this.recallArtistTipLabel.node.active = false;
                this.recallArtistFailTipRichText.node.active = false;
                this.reportArtistTipLabel.node.active = true;
                this.reportArtistFailTipRichText.node.active = false;
                this.gellAllCoinBtn.node.active = false;
                this.confrimBtn.node.active = true;
                this.driveAwayFailTipRichText.node.active = false;
                break;

            case ArtistOperation.ReportArtistFail:
                this.setTitleString("举报艺人");
                this.recallArtistTipLabel.node.active = false;
                this.recallArtistFailTipRichText.node.active = false;
                this.reportArtistTipLabel.node.active = false;
                this.reportArtistFailTipRichText.node.active = true;
                this.gellAllCoinBtn.node.active = false;
                this.confrimBtn.node.active = true;
                this.driveAwayFailTipRichText.node.active = false;
                break;

            case ArtistOperation.DriveAwayArtist:
                this.setTitleString("驱赶艺人");
                this.recallArtistTipLabel.node.active = false;
                this.recallArtistFailTipRichText.node.active = false;
                this.reportArtistTipLabel.node.active = false;
                this.reportArtistFailTipRichText.node.active = false;
                this.gellAllCoinBtn.node.active = true;
                this.confrimBtn.node.active = false;
                this.driveAwayFailTipRichText.node.active = false;
                break;

            case ArtistOperation.DriveAwayArtistFail:
                this.setTitleString("驱赶艺人");
                this.recallArtistTipLabel.node.active = false;
                this.recallArtistFailTipRichText.node.active = false;
                this.reportArtistTipLabel.node.active = false;
                this.reportArtistFailTipRichText.node.active = false;
                this.gellAllCoinBtn.node.active = false;
                this.confrimBtn.node.active = true;
                this.driveAwayFailTipRichText.node.active = true;
                break;

            default:
                break;
        }
        this.operation = operation;
    },

    // LIFE-CYCLE CALLBACKS:
    onLoad () {
        GameModule.homeGuide.on('Fire_state36', () => {
            this.handleConfrimBtn()
        })
    },

    start() {
        
        this.content.y = -cc.view.getVisibleSize().height;

        this.scheduleOnce(() => {
            // 调整弹窗y轴位置，以适应引导系统的UI [-40 ~ 100]
            let s = cc.sequence(cc.moveTo(0.2, 0, 100).easing(cc.easeCubicActionOut()), cc.moveBy(0.05, 0, -20));
            this.content.runAction(s);
        }, 0.1);
    },

    showCollectAnim(pos, colNums) {
        let canvasNode = cc.find("Canvas");
        let grossCoin = GameModule.userInfo.grossCoin;
        let grossCoinPos = grossCoin.node.convertToWorldSpace(cc.v2(grossCoin.node.width/2, grossCoin.node.height/2));
        
        // let colNums = 5
        let vSize = cc.view.getVisibleSize();
        let target = cc.v2(grossCoinPos.x - vSize.width / 2, grossCoinPos.y - vSize.height / 2)
        
        let i = 0;
        let runSt = setInterval(() => {
            if(i == colNums) {
                clearInterval(runSt)
            } else {
                let ran = (Math.random() - 0.5) * 2 * 3;

                let newCoin = cc.instantiate(this.coinPrefab);
                let posX = pos.x - vSize.width / 2;
                let posY = pos.y - vSize.height / 2;
                
                canvasNode.addChild(newCoin)

                newCoin.x = posX + ran * 15;
                newCoin.y = posY + 30 + ran * 15;
                newCoin.active = true;

                newCoin = newCoin.getComponent("LevelHomeCoin")
                newCoin.initAnim()

                let cbDestroy = cc.callFunc(() => {
                    newCoin.node.destroy();
                })

                let act = cc.sequence(cc.moveTo(1, target), cbDestroy)
                newCoin.node.runAction(act.easing(cc.easeIn(2.1)));
                i++
            }
        }, 100);
    },

    handleConfrimBtn() {

        if (this.benefit === 0) {
            this.dissmiss();
        } else {

            let animation = () => {

                let changeTimes = 10;
                let changeUnit = this.benefit === 0 ? 0 : Math.floor(this.benefit / changeTimes);
                // let pos = this.coinNode.convertToWorldSpace(cc.v2(this.coinNode.width/2, this.coinNode.height/2))
                // this.showCollectAnim(pos, changeTimes);
                for (let i = 0; i < changeTimes; i++) {
                    setTimeout(() => {
                        let result = this.benefit - changeUnit;
                        if (i === changeTimes-1) {
                            result = 0;
                            setTimeout(() => { // 延时关闭当前界面
                                this.dissmiss();
                            }, 200);
                        }
                        this.benefit = result;
                    }, 100 * i);
                }
            }

            if (this.operation === ArtistOperation.RecallArtist || 
                this.operation === ArtistOperation.DriveAwayArtist) {
    
                HomeApi.friendExpelRecall(this.artistData.id || this.artistData.uid, (responseData) => { // 召回驱赶艺人成功
                    animation();
                    GameModule.userInfo.grossIncome += this.operationData.benefit;
                    GameEvent.fire(GameNotificationKey.RefreshLevelHomeArtistList, this.uid, this.buildingInfo.buildingId);
                    GameEvent.fire(GameNotificationKey.RefreshResidentArtistList);
                    let opt = (this.operation === ArtistOperation.RecallArtist) ? 6 : 7;
                    GameEvent.fire(GameNotificationKey.NoticeRoleOpt, this.uid, opt);
                }, (code, msg) => {
                    console.log(msg);
                    this.dissmiss();
                });
    
            } else {
    
                if (this.operation === ArtistOperation.ReportArtistSuccess) { // 举报艺人成功
                    HomeApi.friendReportArtist(this.artistData.id || this.artistData.uid, (responseData) => {
                        this.dissmiss();
                        AlertManaget.showArtistReportSuccess(Math.floor(this.operationData.benefit * 0.1));    
                        GameModule.userInfo.grossIncome += Math.floor(this.operationData.benefit * 0.1);
                        GameEvent.fire(GameNotificationKey.NoticeRoleOpt, this.uid, 8);
                    }, (code, msg) => {
                        console.log(msg);
                        this.dissmiss();
                    });
                } else {
                    this.dissmiss();
                }
            }
        }
    },

    dissmiss() {
        let finish = cc.callFunc(() => {
            this.node.destroy();
        }, this);
        let sequence = cc.sequence(cc.scaleTo(0.2, 0, 0).easing(cc.easeBackIn()), finish)
        this.content.runAction(sequence);
    },

    close() {
        this.dissmiss();
    },

    setTitleString(title) {
        this.titleRichText.string = `<outline color=#e8e9e9 width=2><b><color=#584A47>${title}</c></b></outline>`;
    },

    getNickString(nick) {
        this.nickRichText.string = `<color=#584a47>${nick}</c> <img src='50001'/>`;
    },
});
