<!--
    filename: BomSelection.vue
    author: liubin
    date: 2023-11-20 13:23:36
    description:
-->

<template>
	<div class="bom-selection">
		<el-checkbox
			v-for="item in list__inner"
			:key="item.id + randomKey"
			:label="item.name"
			:disabled="item.disabled"
			:checked="item.id === selected"
			@change="(e) => handleChange(item, e)"
			class="sl__body-item"></el-checkbox>
	</div>
</template>

<script>
export default {
	name: 'BomSelection',
	components: {},
	// model: {
	// 	prop: 'selected',
	// 	event: 'update',
	// },
	props: {
		currentSelect: {
			type: String | Number,
			default: null,
		},
		list: {
			type: Array,
			default: () => [],
		},
		equipmentId: {
			type: String,
			default: '',
		},
	},
	data() {
		return {
			list__inner: [],
			selected: null,
			randomKey: Math.random(),
		};
	},
	watch: {
		list: {
			handler(val) {
        if (val) {
          console.log(val);
					this.list__inner = val.map((item) => ({ ...item, disabled: false }));
				}
			},
			deep: true,
			immediate: true,
		},
		currentSelect: {
			handler(val) {
				// val: string
				this.selected = val;
				this.randomKey = Math.random();
				// 更新选中状态
				if (val) {
					this.list__inner.forEach((item) => {
						if (item.id == val) item.disabled = false;
						else item.disabled = true;
					});
				}
			},
			immediate: true,
		},
	},
	methods: {
    handleChange(bomItem, selected) {
      console.log(selected);
			this.list__inner = this.list__inner.map((item) => ({
				...item,
				disabled: selected ? item.id !== bomItem.id : false,
			}));

			if (selected) this.selected = null;
			else this.clearSelected();

			this.$emit('change', this.equipmentId, bomItem.id, selected);
			this.$nextTick(() => {
				this.$forceUpdate();
			});
		},
		clearSelected() {
			console.log('clearSelected');
			this.selected = null;
			this.randomKey = Math.random();
			// this.$emit('update', null);
			// this.$nextTick(() => {
			// 	this.$forceUpdate();
			// });
		},
	},
};
</script>

<style scoped lang="scss">
.bom-selection {
	display: flex;
	flex-direction: column;
	gap: 6px;
	padding: 6px;
}

.sl__body-item {
	margin: 0;
	padding: 3px 6px;
	border-radius: 4px;
	transition: background 0.3s ease-in-out;

	&:hover {
		background: #0001;
	}
}
</style>
