<script setup>

import "@/lib/array.js"
import useUtils from "@/utils/utils.js"
import {ref} from "vue"
import TDivider from "@/components/ui/TDivider.vue";
import TLabel from "@/components/ui/TLabel.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";

const utils = useUtils()

const props = defineProps(["v-methods"])

const addingMethodRef = ref()
const {methods, isAdding, addingMethod} = (function () {
	let methods = props.vMethods
	if (methods == null) {
		methods = []
	}
	return {
		methods: ref(methods),
		isAdding: ref(false),
		addingMethod: ref("")
	}
})()

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

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

	if (addingMethod.value.length == 0) {
		utils.warn("请输入要添加的请求方法", function () {
			addingMethodRef.value.focus()
		})
		return
	}

	// 是否已经存在
	if (methods.value.$contains(addingMethod.value)) {
		utils.warn("此请求方法已经存在，无需重复添加", function () {
			addingMethodRef.value.focus()
		})
		return
	}

	methods.value.push(addingMethod.value)
	cancel()
}

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

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


</script>

<template>
	<div>
		<input type="hidden" name="methodsJSON" :value="JSON.stringify(methods)"/>
		<div v-if="methods.length > 0" class="label-group">
			<TLabel outlined="" v-for="(method, index) in methods">
				{{ method }}
				&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="addingMethod" @keyup.enter="confirm()" @keypress.enter.prevent="1" ref="addingMethodRef" placeholder="如GET" size="10"/>
				</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>GET</CodeLabel>
				、
				<CodeLabel>POST</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>
