<template>
	<div class="w-full p-4 pt-0 box-border flex flex-col gap-2">
		<div
			v-for="(caseItem, index) in cases"
			:key="caseItem.id"
			class="border border-b-0.5px border-b-solid border-gray-200 relative"
			:style="{ paddingLeft: cases[index]!.conditions?.length < 2 ? '60px' : '0' }"
		>
			<div class="absolute text-16px font-bold top-0 left-0">{{ index === 0 ? 'IF' : 'ELIF' }}</div>
			<Condition
				:conditions="cases[index]!.conditions"
				:operator="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>
	</div>
</template>

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

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

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

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

const emit = defineEmits<Emits>()

const cases = computed<ConditionData['cases']>(() => props.data.cases)

const addCase = () => {
	emit('update', {
		...props.data,
		cases: [
			...cases.value,
			{
				id: '',
				conditions: [],
				logical_operator: 'and'
			}
		]
	})
}

const removeCase = (index: number) => {
	emit('update', {
		...props.data,
		cases: cases.value.filter((_, i) => i !== index)
	})
}

const onUpdateConditions = (index: number, conditions: ConditionType[]) => {
	emit('update', {
		...props.data,
		cases: cases.value.map((caseItem, i) => (i === index ? { ...caseItem, conditions } : caseItem))
	})
}

const onUpdateOperator = (index: number, operator: 'and' | 'or') => {
	emit('update', {
		...props.data,
		cases: cases.value.map((caseItem, i) =>
			i === index ? { ...caseItem, logical_operator: operator } : caseItem
		)
	})
}
</script>
