<template>
	<view style="display:inline-block;">
		{{p1}}<text style="font-size:0.6em;">{{p2}}</text><text style="font-size:0.6em;padding-left:0.3em;">{{punit}}</text>
	</view>
</template>

<style scoped>
</style>

<script>
	export default {
		props: {
			value: {
				type: [String, Number],
				default: 0
			},
			unit: {
				type: String,
				default: ''
			}, //元,100,2|万元,1000000,3|亿元,10000000000,3    单位,除数,保留位数
			speed: {
				type: [String, Number],
				default: 30
			},
		},
		data() {
			return {
				p1: 0,
				p2: '',
				punit: '',
			};
		},
		watch: {
			value(newD, oldD) {
				if (this.inter) {
					setTimeout(() => {
						this.fillnum(newD);
					}, 500);
				} else
					this.ani(newD, oldD);
			}
		},
		computed: {
			speeddata() {
				var speed = this.toint(this.speed);
				if(speed < 3)
					speed = 10;
				return speed;
			},
			units() {
				var unitss = this.unit.replace(/\*/g, '').split('|');
				var units = [];
				for (var i in unitss) {
					var u = {};
					var ss = unitss[i].split(',');
					u.unit = ss[0];
					u.bet = parseInt(ss[1]);
					u.fix = parseInt(ss[2]);
					if (isNaN(u.bet))
						u.bet = 1;
					if (u.bet < 1)
						u.bet = 1;
					if (isNaN(u.fix))
						u.fix = 0;
					units.unshift(u);
				}
				return units;
			}
		},
		mounted() {
			this.ani(this.value, -1);
		},
		methods: {
			ani(newD, oldD) {
				if (newD == oldD)
					return;
				var step = (newD - oldD) / this.speeddata;
				var val = parseFloat(oldD);
				var stepi = 0;
				this.inter = setInterval(() => {
					val += step;
					stepi++;
					if (stepi > this.speeddata) {
						clearInterval(this.inter);
						this.inter = null;
						this.fillnum(newD);
					} else
						this.fillnum(val);
				}, 16);
			},
			fillnum(value) {
				value = parseInt(value);
				if (isNaN(value))
					value = 0;
				for (var u in this.units) {
					var val = value / this.units[u].bet;
					if (val < 1 && u < this.units.length - 1)
						continue;
					val = this.tofix(val, this.units[u].fix) + '';
					var ind = val.indexOf('.');
					if (ind === -1) {
						this.p1 = val;
						this.p2 = '';
					} else {
						this.p1 = val.substr(0, ind);
						this.p2 = val.substr(ind);
					}
					this.punit = this.units[u].unit;
					break;
				}
			}
		}
	}
</script>