<script setup>
import {onMounted, ref, watch} from "vue";
import TInputText from "@/components/ui/TInputText.vue";
import TSelect from "@/components/ui/TSelect.vue";
import TOption from "@/components/ui/TOption.vue";

const props = defineProps(["v-name", "v-value", "v-count", "v-unit", "placeholder", "v-min-unit", "maxlength"])
const emits = defineEmits(["change"])

const {duration, countString, units, realMaxLength} = (function () {
	let v = props.vValue
	if (v == null) {
		v = {
			count: props.vCount,
			unit: props.vUnit
		}
	}
	if (typeof (v["count"]) != "number") {
		v["count"] = -1
	}

	let minUnit = props.vMinUnit
	let units = [
		{
			code: "ms",
			name: "毫秒"
		},
		{
			code: "second",
			name: "秒"
		},
		{
			code: "minute",
			name: "分钟"
		},
		{
			code: "hour",
			name: "小时"
		},
		{
			code: "day",
			name: "天"
		}
	]
	let minUnitIndex = -1
	if (minUnit != null && typeof minUnit == "string" && minUnit.length > 0) {
		for (let i = 0; i < units.length; i++) {
			if (units[i].code == minUnit) {
				minUnitIndex = i
				break
			}
		}
	}
	if (minUnitIndex > -1) {
		units = units.slice(minUnitIndex)
	}

	let maxLength = parseInt(props.maxlength)
	if (isNaN(maxLength) || maxLength <= 0) {
		maxLength = 6
	}

	return {
		duration: ref(v),
		countString: ref((v.count >= 0) ? v.count.toString() : ""),
		units: ref(units),
		realMaxLength: ref(maxLength)
	}
})()

const change = function () {
	emits("change", duration.value)
}

watch(countString, function (newValue) {
	let value = newValue.trim()
	if (value.length == 0) {
		duration.value.count = -1
		return
	}
	let count = parseInt(value)
	if (!isNaN(count)) {
		duration.value.count = count
	}
	change()
})

onMounted(() => {
	change()
})

</script>

<template>
	<div class="ui fields inline" style="padding-bottom: 0; margin-bottom: 0">
		<input type="hidden" :name="vName" :value="JSON.stringify(duration)"/>
		<div class="ui field">
			<TInputText type="text" v-model="countString" :maxlength="realMaxLength" :size="realMaxLength" :placeholder="placeholder"/>
		</div>
		<div class="ui field">
			<TSelect v-model="duration.unit" @change="change">
				<TOption v-for="unit in units" :value="unit.code">{{ unit.name }}</TOption>
			</TSelect>
		</div>
	</div>
</template>

<style scoped>

</style>