<template>
	<div class="time-convertor">
		<label v-for="(item,index) in rangeData">
			<InputNumber
				class="input"
				v-model="item.value"
				name
				id
				:key="index"
				:min="item.min"
				:max="item.max"
				size="small"
				@on-change="onChange"
			/>
			{{labelList[item.scaleIndex]}}
		</label>
	</div>
</template>

<script>
import { time } from 'hq-tools'
const scaleList = ['day', 'hour', 'minute', 'second', 'millisecond'];
const steps = [24, 60, 60, 1000, 1]
export default {
	name: 'TimeConvertor',
	props: {
		value: {
			type: Number,
			default: () => {
				return 0
			}
		},
		valueScale: {
			type: 'day' | 'hour' | 'minute' | 'second' | 'millisecond',
			default: () => {
				return 'day'
			}
		},
		range: {
			validator: (value) => {
				if (value.length !== 2) return false;
				const begin = scaleList.indexOf(value[0]);
				const end = scaleList.indexOf(value[1]);
				if (begin < 0 || end < 0 || begin >= end) return false
				return true
			},
			type: Array,
			default: () => {
				return ['day', 'millisecond']
			}
		},
		toFixed: {
			type: Number,
			default: () => {
				return 6;
			}
		}
	},
	data() {
		return {
			labelList: ['日', '小时', '分钟', '秒', '毫秒']
		}
	},
	computed: {
		begin() {
			return scaleList.indexOf(this.range[0])
		},
		end() {
			return scaleList.indexOf(this.range[1])
		},
		data: {
			set(to) {
				let scaleNumber = 1;
				for (let j = scaleList.indexOf(this.valueScale); j < 5; j++) {
					scaleNumber *= steps[j];
				}
				this.$emit('input', Number((to / scaleNumber).toFixed(this.toFixed)));
			},
			get() {
				let value = this.value;
				for (let i = this.begin; i < 5; i++) {
					value *= steps[i];
				}
				return value;
			}
		},
		rangeData: {
			set(to) {
				let value = 0;
				for (let item of to) {
					value += item.value * item.scaleNumber;
				}
				this.data = value;
			},
			get() {
				let list = [];
				let value = this.data;
				for (let i = this.begin; i <= this.end; i++) {
					let scaleNumber = 1;
					for (let j = i; j < 5; j++) {
						scaleNumber *= steps[j]
					}
					let newItem = {
						scaleIndex: i,
						scale: scaleList[i],
						scaleNumber,
						value: Math.floor(value / scaleNumber),
						min: 0,
						max: i === 0 ? 9999 : steps[i - 1] - 1
					};
					list.push(newItem)
					value = value % scaleNumber;
				}

				return list;
			}
		}
	},
	methods: {
		onChange() {
			this.$set(this, 'rangeData', this.rangeData);
		}
	}
}
</script>

<style lang="less" scoped>
.time-convertor {
	display: flex;
	.input {
		width: 60px;
	}
}
</style>