<script setup>

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

const utils = useUtils()

const props = defineProps(["v-replace-values"])

const patternRef = ref()
const {values, isAdding, addingValue} = (function () {
	let values = props.vReplaceValues
	if (values == null) {
		values = []
	}
	return {
		values: ref(values),
		isAdding: ref(false),
		addingValue: ref({"pattern": "", "replacement": "", "isCaseInsensitive": false, "isRegexp": false})
	}
})()

const add = function () {
	isAdding.value = true
	setTimeout(function () {
		patternRef.value.focus()
	})
}

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

const confirm = function () {
	if (addingValue.value.pattern.length == 0) {
		utils.warn("替换前内容不能为空", function () {
			patternRef.value.focus()
		})
		return
	}

	values.value.push(addingValue.value)
	cancel()
}

const cancel = function () {
	isAdding.value = false
	addingValue.value = {"pattern": "", "replacement": "", "isCaseInsensitive": false, "isRegexp": false}
}


</script>

<template>
	<div>
		<input type="hidden" name="replaceValuesJSON" :value="JSON.stringify(values)"/>
		<div class="label-group mb-2">
			<TLabel outlined="" v-for="(value, index) in values">
				<var>{{ value.pattern }}</var><sup v-if="value.isCaseInsensitive" title="不区分大小写"><i class="icon info tiny"></i></sup> =&gt;
				<var v-if="value.replacement.length > 0">{{ value.replacement }}</var><var v-else><span class="small grey">[空]</span></var>&nbsp;
				<a href="" @click.prevent="remove(index)" title="删除"><i class="icon remove small"></i></a>
			</TLabel>
		</div>
		<div v-if="isAdding">
			<table class="ui table definition">
				<tr>
					<td class="title">替换前内容 *</td>
					<td>
						<TInputText type="text" v-model="addingValue.pattern" placeholder="替换前内容" ref="patternRef" @keyup.enter="confirm()" @keypress.enter.prevent="1" class="w-full"/>
					</td>
				</tr>
				<tr>
					<td>替换后内容</td>
					<td>
						<TInputText type="text" v-model="addingValue.replacement" placeholder="替换后内容" @keyup.enter="confirm()" @keypress.enter.prevent="1" class="w-full"/>
					</td>
				</tr>
				<tr>
					<td>忽略大小写</td>
					<td>
						<TCheckboxBinary v-model="addingValue.isCaseInsensitive"></TCheckboxBinary>
					</td>
				</tr>
			</table>

			<div>
				<TButton type="button" secondary="" size="small" @click.prevent="confirm">确定</TButton> &nbsp;
				<a href="" title="取消" @click.prevent="cancel"><i class="icon remove small"></i></a>
			</div>
		</div>
		<div v-if="!isAdding">
			<PlusButton type="button" secondary="" size="small" @click.prevent="add"></PlusButton>
		</div>
	</div>
</template>

<style scoped>
</style>
