<script setup>

import "@/lib/array.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 TLabel from "@/components/ui/TLabel.vue";

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

const addingExtRef = ref()
const {cond, extensions, isAdding, addingExt} = (function () {
	let cond = {
		isRequest: true,
		param: "${requestPathLowerExtension}",
		operator: "not in",
		value: "[]"
	}
	if (props.vCond != null && props.vCond.param == cond.param) {
		cond.value = props.vCond.value
	}

	let extensions = []
	try {
		extensions = JSON.parse(cond.value)
	} catch (e) {

	}

	return {
		cond: ref(cond),
		extensions: ref(extensions), // TODO 可以拖动排序

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

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

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

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

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

	if (addingExt.value.length == 0) {
		return
	}
	if (addingExt.value[0] != ".") {
		addingExt.value = "." + addingExt.value
	}
	addingExt.value = addingExt.value.replace(/\s+/g, "").toLowerCase()
	extensions.value.push(addingExt.value)

	// 清除状态
	cancelAdding()
}

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


</script>

<template>
	<div>
		<input type="hidden" name="condJSON" :value="JSON.stringify(cond)"/>
		<div v-if="extensions.length > 0" class="label-group">
			<TLabel outlined="" v-for="(ext, index) in extensions">{{ ext }}
				<a href="" title="删除" @click.prevent="removeExt(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="6" maxlength="100" v-model="addingExt" ref="addingExtRef" placeholder=".xxx" @keyup.enter="confirmAdding" @keypress.enter.prevent="1" class="w-full"/>
			</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" v-show="!isAdding">
			<TButton secondary="" size="small" type="button" @click.prevent="addExt()">+添加扩展名</TButton>
		</div>
		<p class="comment">扩展名需要包含点（.）符号，例如
			<CodeLabel>.jpg</CodeLabel>
			、
			<CodeLabel>.png</CodeLabel>
			之类。
		</p>
	</div>
</template>

<style scoped>
</style>
