<template>
	<div class="w-full p-4 pt-0 box-border flex flex-col gap-2">
		<div
			v-for="(caseItem, index) in formData.cases"
			:key="caseItem.id"
			class="border border-b-0.5px border-b-solid border-gray-200 relative"
			:style="{ paddingLeft: formData.cases[index]!.conditions?.length < 2 ? '60px' : '0' }"
		>
			<div class="absolute top-0 left-0">
				<div class="text-12px text-gray-500">条件_{{ index + 1 }}</div>
				<div class="text-16px font-bold">{{ index === 0 ? 'IF' : 'ELIF' }}</div>
			</div>
			<Condition
				:conditions="formData.cases[index]!.conditions"
				:operator="formData.cases[index]!.logical_operator"
				@update:conditions="onUpdateConditions(index, $event)"
				@update:operator="onUpdateOperator(index, $event)"
			/>
			<div class="absolute right-0 bottom-8px">
				<el-button link @click="removeCase(index)">
					<Icon icon="lucide:trash-2" />
					<span>删除</span>
				</el-button>
			</div>
		</div>
		<el-button class="w-full" @click="addCase">+ ELIF</el-button>
		<div class="border border-0.5px border-y-solid border-gray-200 py-2">
			<div class="text-16px font-bold">ELSE</div>
			<div class="text-12px text-gray-500 pl-12px">用于定义当所有条件都不满足时的处理逻辑</div>
		</div>
		<NodeRuntimeConfig v-model="formData" />
	</div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import Condition from '../../_base/condition/index.vue'
import { Icon } from '@repo/ui'
import NodeRuntimeConfig from '@/nodes/_base/NodeRuntimeConfig.vue'
import { useSetterModel } from '../_shared/useSetterModel'

import type { ConditionData } from './index'
import type { ConditionType } from '../../Interface'

interface Emits {
	(e: 'update', value: ConditionData): void
}

const props = defineProps<{
	data: ConditionData
	id: string
}>()

const emit = defineEmits<Emits>()

const formData = useSetterModel<ConditionData>(props, emit)
const cases = computed<ConditionData['cases']>(() => formData.value.cases)

const getId = () => {
	const ids = cases.value.map((caseItem) => caseItem.id.split('_')[1]).map(Number)
	const maxId = Math.max(...ids, 0)
	return props.id + '_' + (maxId + 1)
}

const addCase = () => {
	const id = getId()
	formData.value.cases.push({
		id,
		conditions: [],
		logical_operator: 'and'
	})
}

const removeCase = (index: number) => {
	formData.value.cases.splice(index, 1)
}

const onUpdateConditions = (index: number, conditions: ConditionType[]) => {
	formData.value.cases[index]!.conditions = conditions
}

const onUpdateOperator = (index: number, operator: 'and' | 'or') => {
	formData.value.cases[index]!.logical_operator = operator
}
</script>
