<template>
	<div class="assembly-suspension">
		<div
			class="box"
			v-for="(item, index) in value"
			:key="index"
			@contextmenu.stop.prevent="open($event, index)"
		>
			<div class="menu">
				<cl-upload
					text="上传图标"
					v-model="value[index].icon"
					:size="[60, 60]"
					@success="onChange"
				/>
				<div class="ml-10">
					<assembly-link
						:prepend="false"
						v-model="value[index].link"
						@change="onChange"
					/>
					<span class="ml-10 text-warning">{{ isFirstButton(index) }}</span>
				</div>
			</div>
		</div>
		<div class="add" @click="add">
			<el-button link type="primary">添加</el-button>
		</div>
	</div>
</template>

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

const props = defineProps({
	modelValue: {
		type: Object as PropType<Form.Suspension[]>,
		default: () => {
			return [
				{
					icon: "https://tsb-yx.oss-cn-guangzhou.aliyuncs.com/app/mini/float-menu.png",
					tips: "宽高128px",
					link: {
						name: "",
						type: "",
						appid: "",
						page: ""
					}
				}
			];
		}
	}
});
const emit = defineEmits(["update:modelValue"]);

// 判断按钮数量是否超过一个
const isExpand = computed(() => value.value.length > 1);

// 判断当前按钮是否为第一个，并且作为展开按钮
const isFirstButton = (index: number) => {
	if (index === 0 && isExpand.value) {
		return "默认第一个为展开按钮不跳转";
	}
	return value.value[index].tips;
};
const value = ref(props.modelValue);
function add() {
	value.value.push({
		icon: "",
		tips: "宽度128px",
		link: {
			name: "",
			type: "",
			appid: "",
			page: ""
		}
	});
	onChange();
}

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-suspension {
	margin-bottom: 10px;

	.box {
		box-sizing: border-box;
		margin-bottom: 10px;
		background-color: #f6f7fa;
		border-radius: 10px;
		padding: 6px;
		.menu {
			padding: 10px;
			background-color: #ffffff;
			display: flex;
			justify-content: start;
			align-items: center;
			border-radius: 6px;
		}
	}
	.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;
	}
	.ml-10 {
		margin-left: 10px;
	}
	.text-warning {
		color: var(--el-color-warning);
	}
}
</style>
