
const DWTool = require("../utils/DWTool");
const AlertManager = require('../utils/AlertManager');
const { GameNotificationKey, ArtistTrainItemSkillStyle } = require('../utils/GameEnum');
const ArtistTrainApi = require('../net/ArtistTrainApi');
const GameModule = require('../utils/GameModule')

var AristTrainState = cc.Enum({
    Invalid: 0,
    Stay: 1,
    Training: 2,
    Completion: 3
});

cc.Class({
    extends: cc.Component,

    properties: {

        trainBgSprite: cc.Sprite,

        trainSprite: cc.Sprite,

        trainBtn: cc.Button,

        trainBtnSprite: cc.Sprite,

        trainBtnSpriteFrames: [cc.SpriteFrame],

        contentLabel: cc.Label,

        trainCostNode: cc.Node,

        costLabel: cc.Label,

        recuperateLabel: cc.Label,

        sandclockLabel: cc.Label,

        refreshBtn: cc.Button,

        confirmBtn: cc.Button,

        trainSlider: cc.Slider,

        trainSliderTimeLabel: cc.Label,

        trainProgress: cc.Sprite,
        
        // 技能
        skillNode: cc.Node,

        diamondRefreshLabel: cc.Label,

        countDown: {
            get: function() {
                if (!this._countDown) {
                    this._countDown = 0;
                }
                return this._countDown;
            },
            set: function (value) {
                this._countDown = value;
                this.trainSliderTimeLabel.string = DWTool.calculateTime(this._countDown);
                this._preCountDown = this._countDown;
            }
        },
    },

    init(targetUid, data, levelZIndex) {
        
        if (arguments.length < 3) {
            throw new Error("init Missing parameter...");
        }

        this.targetUid = targetUid;
        this.data = data;
        this.levelZIndex = levelZIndex;

        this.contentLabel.string = data.msg;
        
        this.recuperateLabel.string = data.ticket;
        this.costLabel.string = DWTool.coinParse(data.coin);
        this.sandclockLabel.string = DWTool.calculateTime(data.cd / 1000);

        if (GameModule.userInfo.grossIncome > data.coin) {
            this.trainBtn.getComponent(cc.Button).interactable = true;
            this.trainBtnSprite.spriteFrame = this.trainBtnSpriteFrames[1];
        } else {
            this.trainBtn.getComponent(cc.Button).interactable = false;
            this.trainBtnSprite.spriteFrame = this.trainBtnSpriteFrames[0];
        }
        
        let timestamp = Date.parse(new Date());
        if (timestamp > data.cdEnd) {
            this.trainSlider.progress = 1.0;
            this.trainSliderTimeLabel.string = DWTool.calculateTime(0);
        } else {
            let startTime = data.cdEnd - data.cd;
            this._currentTime = (timestamp - startTime) / 1000;
            this.countDown = data.cd / 1000;
        }

        this.setSkillLayout();
        
        this.diamondRefreshLabel.string = `${data.diamond} 加速`;

        DWTool.loadResSpriteFrame(`./artistTrain/${data.quality}`)
        .then((result) => {
            this.trainBgSprite.spriteFrame = result;
        });

        DWTool.loadResSpriteFrame(`./artistTrain/${data.picId}`)
        .then((result) => {
            this.trainSprite.spriteFrame = result;
        });

        if (data.status == 0) {
            this.setState(AristTrainState.Stay);
        } else if (data.status == 1) {
            this.setState(AristTrainState.Training);
        } else if (data.status == 2) {
            this.setState(AristTrainState.Completion);
        } else {
            this.setState(AristTrainState.Invalid);
        }
    },

    // LIFE-CYCLE CALLBACKS:
    onLoad () {

        this._width = this.trainProgress.node.width;

        this.showRechargeEvent = _.debounce(() => {
            AlertManager.showRechargeAlert(this.levelZIndex);
        }, 1000, true);
    },

    startTrain() {

        if (this.state === AristTrainState.Stay) {
            GameModule.userInfo.grossIncome -= this.data.coin;
            GameEvent.fire(GameNotificationKey.BeginArtistTrain, this.data.id);
        }

    },

    setSkillLayout() {

        DWTool.loadResPrefab("./prefabs/artist_train_item_skill")
        .then((prefab) => {
            
            if (this.data.addCharm != 0) {
                let item = cc.instantiate(prefab);
                this.skillNode.addChild(item);
                item.getComponent('ArtistTrainItemSkill').init(ArtistTrainItemSkillStyle.Charm, this.data.addCharm);
            }

            if (this.data.addAbility != 0) {
                let item = cc.instantiate(prefab);
                this.skillNode.addChild(item);
                item.getComponent('ArtistTrainItemSkill').init(ArtistTrainItemSkillStyle.Ability, this.data.addAbility);
            }

            if (this.data.addEffect != 0) {
                let item = cc.instantiate(prefab);
                this.skillNode.addChild(item);
                item.getComponent('ArtistTrainItemSkill').init(ArtistTrainItemSkillStyle.Effect, this.data.addEffect);
            }
        });
    },

    refreshTrainTime() {
        ArtistTrainApi.missionSpeedUp(this.targetUid, this.data.id, () => {
            this.countDown = this._currentTime + 0.2;
        });
    },

    confirm() {
        GameEvent.fire(GameNotificationKey.ArtistTrainCompletion, this.data.id);
        AlertManager.showArtistTrainCompletion(this.data, this.levelZIndex);
    },

    setState(state) {

        if (this.state === state) { return; }

        switch (state) {
            case AristTrainState.Stay:
                this.trainBtn.node.active = true;
                this.refreshBtn.node.active = false;
                this.trainSlider.node.active = false;
                this.trainCostNode.active = true;
                this.confirmBtn.node.active = false;
                this.trainSliderTimeLabel.node.active = false;
                break;

            case AristTrainState.Training:
                this.trainBtn.node.active = false;
                this.refreshBtn.node.active = true;
                this.trainSlider.node.active = true;
                this.trainCostNode.active = false;
                this.confirmBtn.node.active = false;
                this.trainSliderTimeLabel.node.active = true;
                break;

            case AristTrainState.Completion: 
                this.trainBtn.node.active = false;
                this.refreshBtn.node.active = false;
                this.trainCostNode.active = false;
                this.trainSlider.node.active = true;
                this.confirmBtn.node.active = true;
                this.trainSliderTimeLabel.node.active = false;
                break;

            case AristTrainState.Invalid:
                this.trainBtn.node.active = false;
                this.refreshBtn.node.active = false;
                this.trainCostNode.active = false;
                this.trainSlider.node.active = false;
                this.confirmBtn.node.active = false;
                this.trainSliderTimeLabel.node.active = false;
                break;

            default:
                break;
        }

        this.state = state;
    },

    update(dt) {

        if (this.state === AristTrainState.Training) {
            
            // 进度条走完, 开始生产金币
            if (Math.floor(this.trainSlider.progress) != 1) {

                this._currentTime += dt;

                if (Math.floor(this._currentTime) > this.countDown) {
                    this._currentTime = this.countDown;
                }

                let progress = this._currentTime / this.countDown;
                if (Math.floor(progress) === 1) {
                    this.trainSlider.progress = 1;
                } else {
                    this.trainSlider.progress = progress;
                }

                let resultCountDown = this.countDown - Math.floor(this._currentTime);
                if (this._preCountDown !== resultCountDown) {
                    this.trainSliderTimeLabel.string = DWTool.calculateTime(resultCountDown);
                    this._preCountDown = resultCountDown;
                }
                
                this.trainProgress.node.width = this._width * this.trainSlider.progress;

            } else {
                this.setState(AristTrainState.Completion);
            }   
        }
    },
});
