<template>
	<div class="assembly-menus">
		<div>
			<div class="item" v-for="(item, index) in value" :key="index">
				<div @contextmenu.stop.prevent="open($event, index)">
					<assembly-menu
						iconTips="建议尺寸200px*200px"
						v-model="value[index]"
						:maxlength="4"
						@change="onChange"
					/>
				</div>
			</div>
		</div>
		<div class="add" @click="add">
			<el-button link type="primary">添加({{ value.length }}/20)</el-button>
		</div>
	</div>
</template>

<script lang="ts" name="assembly-menus" setup>
import { cloneDeep } from "lodash-es";
import { ref, type PropType } from "vue";
import { ElMessage } from "element-plus";
import { ContextMenu } from "@cool-vue/crud";
import { Form } from "../../types/form";

const props = defineProps({
	modelValue: {
		type: Array as PropType<Form.Menu[]>,
		default: () => []
	}
});

const emit = defineEmits(["update:modelValue"]);

const value = ref(props.modelValue);

function add() {
	if (value.value.length >= 20) {
		ElMessage.error("最多添加20个按钮");
		return;
	}
	value.value.push({
		text: "按钮",
		useText: true,
		mode: "mode-1",
		link: {
			page: "",
			appid: "",
			type: "",
			name: ""
		},
		icon: "",
		color: "#000",
		backgroundColor: "#fff"
	});
}

function open(e: any, index: number) {
	ContextMenu.open(e, {
		list: [
			{
				label: "删除按钮",
				callback(done) {
					value.value.splice(index, 1);
					onChange();
					done();
				}
			},
			{
				label: "复制按钮",
				callback(done) {
					const clonedItem = cloneDeep(value.value[index]);
					// 在index之后的位置插入clonedItem
					value.value.splice(index + 1, 0, clonedItem);
					onChange();
					done();
				}
			}
		]
	});
}

function onChange() {
	emit("update:modelValue", value.value);
}
</script>

<style lang="scss" scoped>
.assembly-menus {
	padding: 0;
	box-sizing: border-box;
	margin-bottom: 10px;

	.tips {
		font-size: 12px;
		color: #bfbfbf;
	}
	.item {
		margin-top: 20px;
	}
	.item:nth-child(1) {
		margin-top: 0;
	}
	.add {
		margin-top: 20px;
		display: flex;
		align-items: center;
		justify-content: center;
		height: 30px;
		border: 1px solid var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
	}
}
</style>
