<template>
	<div class="form-input-params">
		<cl-svg name="add" class="btn-icon is-rt" @click="add()" v-if="!disabled" />

		<div
			class="item"
			v-for="(item, index) in list"
			:key="index"
			:class="{
				'is-error': errFields.includes(item.field)
			}"
		>
			<div class="d">
				<el-input
					v-model="item.field"
					placeholder="变量名"
					class="name"
					clearable
					:disabled="!editField"
				/>
			</div>

			<div class="d">
				<tools-var
					v-model="item.name"
					v-model:node-id="item.nodeId"
					v-model:type="item.type"
					v-model:value="item.value"
					:inputable="varInputable"
				/>
			</div>

			<cl-svg name="delete" class="btn-icon" @click="remove(index)" v-if="!disabled" />
		</div>

		<el-text v-if="isEmpty(list) && placeholder" type="info" size="small">
			<el-icon> <warning /> </el-icon>
			{{ placeholder }}
		</el-text>
	</div>
</template>

<script setup lang="ts" name="node-base-form-input-params">
import type { FlowField } from "/$/flow/types";
import { useModel, type PropType, computed } from "vue";
import ToolsVar from "/$/flow/components/tools/var.vue";
import { isEmpty } from "lodash-es";
import { Warning } from "@element-plus/icons-vue";

const props = defineProps({
	modelValue: {
		type: Array as PropType<FlowField[]>,
		default: () => []
	},
	field: {
		type: String,
		default: "arg"
	},
	// 允许编辑命名
	editField: {
		type: Boolean,
		default: true
	},
	// 禁用
	disabled: Boolean,
	// 占位内容
	placeholder: String,
	// 自定义输入值
	varInputable: Boolean
});

const list = useModel(props, "modelValue");

// 是否有相同命名
const errFields = computed(() => {
	const arr: string[] = [];

	list.value.forEach((a, i) => {
		const n = list.value.findIndex((b) => b.field == a.field);

		if (n >= 0 && i != n) {
			arr.push(a.field);
		}
	});

	return arr;
});

let id = 1;

// 添加
function add() {
	list.value.push({
		field: `${props.field}${++id}`
	});
}

// 移除
function remove(index: number) {
	list.value.splice(index, 1);
}
</script>

<style lang="scss" scoped>
.form-input-params {
	.item {
		display: flex;
		align-items: center;
		margin-bottom: 5px;

		.d {
			margin-right: 5px;
			flex: 1;
			overflow: hidden;
		}

		&:last-child {
			margin-bottom: 0;
		}

		&.is-error {
			.d {
				&:first-child {
					:deep(.el-input__wrapper) {
						box-shadow: 0 0 0 1px var(--el-color-danger) inset;
					}
				}
			}
		}
	}
}
</style>
