<template>
	<section>
		<draggable v-model="value" :item-key="itemKey" animation="200" :group="group" handle=".item-rank">
			<template #item="{ element, index }">
				<div class="draggable-item">
					<div class="item-content">
						<el-icon size="50" class="item-rank">
							<component :is="'pi-icon-move-area'"/>
						</el-icon>
						<div class="item-value">
							<slot v-bind="{ element, index }"></slot>
						</div>
					</div>
					<el-icon v-if="showDel" size="28" class="item-close" @click="remove(index)">
						<component :is="'el-icon-CircleCloseFilled'"/>
					</el-icon>
				</div>
			</template>
		</draggable>
		<div v-if="showAdd" class="add">
			<el-link :underline="false" type="primary" icon="el-icon-circle-plus" @click="add">添加规则</el-link>
		</div>
	</section>
</template>

<script setup>
import draggable from 'vuedraggable'
import {computed} from "vue";

defineOptions({
	name: "piDraggable"
})
const emit = defineEmits(['update:modelValue'])
const props = defineProps({
	modelValue: {type: Array},
	group: {type: Object},
	itemKey: {type: String, default: "index"},
	showAdd: {type: Boolean, default: true},
	showDel: {type: Boolean, default: true},
	template: {type: Object, default: {}}
})

const value = computed({
	get() {
		return props.modelValue
	},
	set(value) {
		emit('update:modelValue', value)
	}
})

function remove(index) {
	value.value.splice(index, 1)
}

function add() {
	value.value.push(JSON.parse(JSON.stringify(props.template)))
}

</script>

<style lang="scss" scoped>
.draggable-item {
	margin: 0 10px 15px 0;
	position: relative;

	.item-content {
		display: flex;
		align-items: center;
		padding: 10px;
		border: 1px solid #eeeeee;
		border-radius: 8px;
	}

	.item-rank {
		cursor: move;
		color: #9E9E9E;
		width: 50px;
	}

	.item-value {
		flex: 1;
	}

	.item-close {
		position: absolute;
		cursor: pointer;
		color: #9E9E9E;
		top: -14px;
		right: -12px;
	}
}

.add {
	padding: 0 10px 10px 20px;
	text-align: center;
}
</style>
