<script setup>

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

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

const addingMimeTypeRef = ref()
const {cond, mimeTypes, isAdding, addingMimeType} = (function () {
	let cond = {
		isRequest: false,
		param: "${response.contentType}",
		operator: "mime type",
		value: "[]"
	}
	if (props.vCond != null && props.vCond.param == cond.param) {
		cond.value = props.vCond.value
	}
	return {
		cond: ref(cond),
		mimeTypes: ref(JSON.parse(cond.value)), // TODO 可以拖动排序

		isAdding: ref(false),
		addingMimeType: ref("")
	}
})()

const addMimeType = function () {
	isAdding.value = !isAdding.value

	if (isAdding.value) {
		setTimeout(function () {
			addingMimeTypeRef.value.focus()
		}, 100)
	}
}

const cancelAdding = function () {
	isAdding.value = false
	addingMimeType.value = ""
}

const confirmAdding = function () {
	// TODO 做更详细的校验
	// TODO 如果有重复的则提示之

	if (addingMimeType.value.length == 0) {
		return
	}
	addingMimeType.value = addingMimeType.value.replace(/\s+/g, "")
	mimeTypes.value.push(addingMimeType.value)

	// 清除状态
	cancelAdding()
}

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

watch(mimeTypes.value, function () {
	cond.value.value = JSON.stringify(mimeTypes.value)
})
</script>

<template>
	<div>
		<input type="hidden" name="condJSON" :value="JSON.stringify(cond)"/>
		<div v-if="mimeTypes.length > 0" class="label-group">
			<TLabel outlined="" v-for="(mimeType, index) in mimeTypes">{{ mimeType }}&nbsp;
				<a href="" title="删除" @click.prevent="removeMimeType(index)"><i class="icon remove"></i></a></TLabel>
			<TDivider></TDivider>
		</div>
		<div class="ui fields inline" v-if="isAdding">
			<div class="ui field">
				<TInputText type="text" size="16" maxlength="100" v-model="addingMimeType" ref="addingMimeTypeRef" placeholder="类似于image/png" @keyup.enter="confirmAdding" @keypress.enter.prevent="1"/>
			</div>
			<div class="ui field">
				<TButton secondary="" size="small" type="button" @click.prevent="confirmAdding">确认</TButton>
				<a href="" title="取消" @click.prevent="cancelAdding"><i class="icon remove"></i></a>
			</div>
		</div>
		<div style="margin-top: 1em">
			<TButton secondary="" size="small" type="button" @click.prevent="addMimeType()">+添加MimeType</TButton>
		</div>
		<p class="comment">服务器返回的内容的MimeType，比如
			<CodeLabel>text/html</CodeLabel>
			、
			<CodeLabel>image/*</CodeLabel>
			等。
		</p>
	</div>
</template>

<style scoped>
</style>
