<template>
	<view class="cu-list">
		<scroll-view
			id="cu-list"
			style="width: 100%;"
			@scroll="scrollFunc"
			:scroll-left="scrollLeft"
			scroll-with-animation
			enable-flex
			class="cu-list-content flex bg-white"
			:class="{'fixed':fixed}"
			:style="{top:top}"
			scroll-x="true"
		>
			<view
				class="item text-center padding-lr"
				v-for="(item, index) in list"
				@click="change(index)"
				:id="'cu-list-' + index"
				style="line-height: 60upx;box-sizing: border-box;"
			>
				{{ item.label }}
			</view>
			<!-- 下标 -->
			<view :style="{ left: barLeft + 'px', width: barWidth + 'px' }" class="bar"></view>
		</scroll-view>
	</view>
</template>

<script>
export default {
	props: {
		value: { type: String / Number, default: '0' },
		list: { type: Array, default: () => [] },
		fixed:{tryp:Boolean,default:false},
		top:{type:String,default:'0px'}
	},
	data() {
		return {
			scrollLeft: 0,
			moveTo: 0, //滚动轴的left
			// 下标
			barLeft: 0,
			barWidth: 0
		};
	},
	watch:{
		value:{
			handler(newVal){
				console.log( newVal)
				this.getRect(newVal);
			},
			deep:true
		}
	},
	methods: {
		scrollFunc(e) {
			if (e) this.moveTo = e.detail.scrollLeft;
		},
		async getRect(key) {
			// scrollview的宽度
			let scrollDom = await this.dom('#cu-list');
			let scrollWidth = scrollDom.width;
			// 计算下标的位置
			let widthList = [],
				barLeft = 0;
			this.list.some((item, index) => {
				widthList.push(this.dom(`#cu-list-${index}`));
				if (index == key) return true;
				return false;
			});
			widthList = await Promise.all(widthList);
			let subLeft = 0,
				subWidth = 0;
			widthList.forEach((item, index, arr) => {
				if (index < arr.length - 1) barLeft += item.width;
				if (index == arr.length - 1) {
					this.barWidth = item.width / 2;
					barLeft += item.width / 4;
					subLeft = item.left;
					subWidth = item.width / 2;
				}
			});
			// 计算滚动
			this.barLeft = barLeft;
			this.scrollLeft = subLeft - scrollWidth / 2 + this.moveTo + subWidth;
		},

		dom(ele) {
			return new Promise((resolve, reject) => {
				this.createSelectorQuery()
					.select(ele)
					.boundingClientRect(rect => {
						resolve(rect);
					})
					.exec();
			});
		},
		change(index) {
			if (index == this.value) return false;
			this.$emit('change', index);
			// this.getRect(index);
		}
	}
};
</script>

<style lang="scss" scoped>
.cu-list {
	height: 60upx;
	.cu-list-content {
		position: relative;
		height: 60upx;
		width: 100vw;
		flex-wrap: nowrap;
		.item {
			white-space: nowrap;
		}
		.bar {
			transition: left 0.3s linear;
			border-bottom: 6upx solid #f03;
			position: absolute;
			top: 54upx;
			z-index: 100;
		}
	}
	.fixed{
		position: fixed !important;
		z-index: 9999;
		left: 0;
	}
}
</style>
