<template>
	<div class="pi-select">
		<div v-if="initloading" class="pi-select-loading">
			<el-icon class="is-loading">
				<el-icon-loading/>
			</el-icon>
		</div>
		<el-cascader ref="address" v-model="value" :props="props" style="width: 100%;" filterable clearable
					 @change="valueChange()"/>
	</div>
</template>

<script>
export default {
	props: {
		modelValue: {
			type: Object,
			default: () => {}
		},
		level: {
			type: Number,
			default: 3,
		}
	},
	data() {
		const _self = this;
		return {
			initloading: false,
			props: {
				lazy: true,
				async lazyLoad(node, resolve) {
					const {level, value} = node
					let address = await _self.getAddress(value || 0)
					address = address.map((item) => ({
						area_name: item.area_name,
						area_code: item.area_code,
						leaf: level >= _self.level - 1,
					}))
					resolve(address)
				},
				label: "area_name",
				value: "area_code",
				multiple: false
			},
			value: null
		}
	},
	watch: {
		modelValue: {
			handler(newValue) {
				if (!newValue) return;
				this.value = newValue
			},
			immediate: true
		},
	},
	created() {
		if (this.hasValue()) {
			this.initloading = true
			this.getAddress()
		}
	},
	methods: {
		async getAddress(area_code) {
			const res = await this.$API.system.region.option({parent_code: area_code})
			return res.data;
		},
		valueChange() {
			let address = this.$refs.address.getCheckedNodes()[0]
			this.$emit('update:modelValue', this.value)
			this.$emit('onChange', address)
		}
	}
}
</script>

<style scoped>
.pi-select {
	display: inline-block;
	position: relative;
}

.pi-select-loading {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: #fff;
	z-index: 100;
	border-radius: 5px;
	border: 1px solid #EBEEF5;
	display: flex;
	align-items: center;
	padding-left: 10px;
}

.pi-select-loading i {
	font-size: 14px;
}

.dark .pi-select-loading {
	background: var(--el-bg-color-overlay);
	border-color: var(--el-border-color-light);
}
</style>
