import { gameMethod } from "../../../common/gameMethod";
import GameMath from "../../../utils/GameMath";
const { ccclass, property, menu } = cc._decorator;


@ccclass
@menu('Label/LabelAnim')
export default class LabelAnim extends cc.Component {
    curVal = { val: 0 }

    showAnim: boolean = false
    type: number = 0// 0 完整  1缩写
    realStr: string = ""

    backupValue: number = 0 // 备份的数据,当多次触发时,第二次触发时的初始值直接变成第一次的最终值
    start() {
        //this.setLabelByType()
    }
    onDisable() {
        cc.Tween.stopAllByTarget(this.curVal)
    }
    update(dt) {
        if (!this.showAnim) { return }
        this.setLabelByType()
    }
    //
    initLabel(val: number, type: number = 0, realStr: string = "") {
        this.realStr = ""
        this.curVal = { val: val }
        this.type = type
        this.setLabelByType()
    }
    setLabel(val: number, time: number = 0.5, type: number = 0, realStr: string = "",) {
        if (this.showAnim) {
            cc.Tween.stopAllByTarget(this.curVal.val)
            this.curVal.val = this.backupValue
        }
        this.backupValue = val
        this.showAnim = true
        this.type = type
        this.realStr = realStr
        cc.tween(this.curVal).to(time, { val: val }).
            call(() => {
                this.curVal = { val: val }
                this.showAnim = false
                this.setLabelByType()
            }).
            start()
    }

    private setLabelByType() {
        if (this.node == null || this.node.isValid == false) { return }
        let str = Math.round(this.curVal.val)
        if (gameMethod.isEmpty(this.node) || gameMethod.isEmpty(this.node.getComponent(cc.Label))) return
        switch (this.type) {
            case 0:
                if (this.realStr.length > 0) {
                    this.node.getComponent(cc.Label).string = this.realStr.replace("%{0}", str.toString())
                } else {
                    this.node.getComponent(cc.Label).string = str.toString()
                }
                break
            case 1:
                if (this.realStr.length > 0) {
                    this.node.getComponent(cc.Label).string = this.realStr.replace("%{0}", GameMath.showNum(str, 100000000))
                } else {
                    this.node.getComponent(cc.Label).string = GameMath.showNum(str, 100000000)
                }
                break
        }
    }
}
