<template>
	<div class="assembly-banner">
		<el-row class="item" :gutter="6" v-for="(item, index) in value" :key="index">
			<el-col>
				<div>
					<div class="icon-row">
						<cl-upload
							:size="[80, 80]"
							v-model="item.pic"
							@success="onChange"
						></cl-upload>
						<div>
							<el-button
								:icon="Top"
								text
								circle
								v-if="index"
								type="primary"
								@click="top(index)"
							></el-button>
							<el-button
								:icon="Bottom"
								text
								circle
								v-if="index != value.length - 1"
								type="primary"
								@click="bottom(index)"
							></el-button>
							<el-button
								:icon="Delete"
								text
								circle
								type="danger"
								@click="del(index)"
							></el-button>
						</div>
					</div>
					<div class="tips">图片宽度 750px 高度不限制</div>
				</div>
			</el-col>
			<el-col>
				<assembly-link v-model="item.link"></assembly-link>
			</el-col>
		</el-row>
		<div class="add" @click="add">
			<el-button link type="primary">添加</el-button>
		</div>
	</div>
</template>
<script lang="ts" name="assembly-banner" setup>
import { ref, type PropType } from "vue";
import { Delete, Top, Bottom } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { Form } from "../../types/form";

const props = defineProps({
	modelValue: {
		type: Array as PropType<{ pic: string; link: Form.Link }[]>,
		default: () => [
			{
				pic: "",
				link: {
					name: "",
					type: "",
					appid: "",
					page: ""
				}
			}
		]
	}
});

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

const value = ref<any[]>(props.modelValue);
function add() {
	value.value.push({
		pic: "",
		link: {
			name: "",
			type: "",
			appid: "",
			page: ""
		}
	});
	onChange();
}

function top(index: number) {
	if (index) {
		swap(JSON.parse(JSON.stringify(value.value)), index, index - 1);
	}
}

function bottom(index: number) {
	if (value.value.length >= index) {
		swap(JSON.parse(JSON.stringify(value.value)), index, index + 1);
	}
}
// 位置互换
function swap(arr: any[], index1: number, index2: number) {
	[arr[index1], arr[index2]] = [arr[index2], arr[index1]];
	value.value = arr;
	onChange();
}

function del(index: number) {
	if (value.value.length > 1) {
		value.value.splice(index, 1);
		onChange();
	} else {
		ElMessage.error("必须保留一张图片");
	}
}
function onChange() {
	emit("update:modelValue", value.value);
}
</script>

<style lang="scss" scoped>
.assembly-banner {
	.item {
		border: 1px solid var(--el-border-color);
		border-radius: 6px;
		padding: 10px;
		box-sizing: border-box;
		margin-bottom: 10px;
		.icon-row {
			display: flex;
			justify-content: space-between;
			align-items: flex-start;
		}
		.tips {
			font-size: 12px;
			color: #bfbfbf;
		}
	}

	.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>
