<script setup>

import "@/lib/array.js"
import useUtils from "@/utils/utils.js"
import {ref} from "vue"
import TDivider from "@/components/ui/TDivider.vue";
import TInputText from "@/components/ui/TInputText.vue";
import TButton from "@/components/ui/TButton.vue";
import CodeLabel from "@/components/common/CodeLabel.vue";
import PlusButton from "@/components/common/PlusButton.vue";
import TLabel from "@/components/ui/TLabel.vue";

const utils = useUtils()

const props = defineProps(["v-status-list"])

const addingStatusRef = ref()
const {statusList, isAdding, addingStatus} = (function () {
	let statusList = props.vStatusList
	if (statusList == null) {
		statusList = []
	}
	return {
		statusList: ref(statusList),
		isAdding: ref(false),
		addingStatus: ref("")
	}
})()

const add = function () {
	isAdding.value = true
	setTimeout(function () {
		addingStatusRef.value.focus()
	}, 100)
}

const confirm = function () {
	// 删除其中的空格
	addingStatus.value = addingStatus.value.replace(/\s/g, "").toUpperCase()

	if (addingStatus.value.length == 0) {
		utils.warn("请输入要添加的状态码", function () {
			addingStatusRef.value.focus()
		})
		return
	}

	// 是否已经存在
	if (statusList.value.$contains(addingStatus.value)) {
		utils.warn("此状态码已经存在，无需重复添加", function () {
			addingStatusRef.value.focus()
		})
		return
	}

	// 格式
	if (!addingStatus.value.match(/^\d{3}$/)) {
		utils.warn("请输入正确的状态码", function () {
			addingStatusRef.value.focus()
		})
		return
	}

	statusList.value.push(parseInt(addingStatus.value, 10))
	cancel()
}

const remove = function (index) {
	statusList.value.$remove(index)
}

const cancel = function () {
	isAdding.value = false
	addingStatus.value = ""
}


</script>

<template>
	<div>
		<input type="hidden" name="statusListJSON" :value="JSON.stringify(statusList)"/>
		<div v-if="statusList.length > 0" class="label-group">
			<TLabel outlined="" v-for="(status, index) in statusList">
				{{ status }}
				&nbsp; <a href="" title="删除" @click.prevent="remove(index)"><i class="icon remove small"></i></a>
			</TLabel>
			<TDivider></TDivider>
		</div>
		<div v-if="isAdding">
			<div class="ui fields inline">
				<div class="ui field">
					<TInputText type="text" v-model="addingStatus" @keyup.enter="confirm()" @keypress.enter.prevent="1" ref="addingStatusRef" placeholder="如200" size="3" maxlength="3" style="width: 5em"/>
				</div>
				<div class="ui field">
					<TButton secondary="" size="small" type="button" @click.prevent="confirm">确定</TButton>
					&nbsp; <a href="" title="取消" @click.prevent="cancel"><i class="icon remove small"></i></a>
				</div>
			</div>
			<p class="comment">格式为三位数字，比如
				<CodeLabel>200</CodeLabel>
				、
				<CodeLabel>404</CodeLabel>
				等。
			</p>
			<TDivider></TDivider>
		</div>
		<div style="margin-top: 0.5em" v-if="!isAdding">
			<PlusButton secondary="" size="small" type="button" @click.prevent="add">+</PlusButton>
		</div>
	</div>
</template>

<style scoped>
</style>
