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

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

const addingExtRef = ref()
const {
	cond, extensions, isAdding, addingExt
} = (function () {
	let cond = {
		isRequest: true,
		param: "${requestPathLowerExtension}",
		operator: "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) {
		extensions = []
	}

	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
	}

	addingExt.value.split(/[,;，；|]/).forEach(function (ext) {
		ext = ext.trim()
		if (ext.length > 0) {
			if (ext[0] != ".") {
				ext = "." + ext
			}
			ext = ext.replace(/\s+/g, "").toLowerCase()
			extensions.value.push(ext)
		}
	})

	// 清除状态
	cancelAdding()
}

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

watch(extensions.value, function () {
	cond.value.value = JSON.stringify(extensions.value)
})

</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 small"></i></a></TLabel>
			<TDivider></TDivider>
		</div>
		<div class="ui fields inline" v-if="isAdding">
			<div class="ui field">
				<TInputText type="text" size="30" maxlength="200" v-model="addingExt" ref="addingExtRef" placeholder=".xxx, .yyy" @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">&nbsp;<i class="icon remove"></i></a>
			</div>
		</div>
		<div 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>
